3
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT ProductName, ProductPrice FROM Product WHERE (@type LIKE '%' + @seach + '%')">
<SelectParameters>
    <asp:QueryStringParameter Name="type" QueryStringField="type" />
    <asp:QueryStringParameter Name="seach" QueryStringField="search" />
</SelectParameters>
</asp:SqlDataSource>

The problem is I cannot get any return results at all because og @type. If I change the @type to ProductName it works fine, but I want the @type value be a dynamic value that can choose by user and is passed in by using QueryString. How can I solve this kind of problem?

2 Answers 2

2

You can you dynamic SQL in this case.

Change the select query to stored procedure say -

CREATE PROCEDURE usp_GetData
    @type VARCHAR(100),
    @search NVARCHAR(max)
AS 
    BEGIN

        DECLARE @SQLQuery AS NVARCHAR(max)

        SET @SQLQuery = 'SELECT ProductName, ProductPrice FROM Product WHERE ( ['
            + @type + '] LIKE ''%' + @search + '%'')'

        PRINT @SQLQuery
        EXECUTE sp_executesql @sqlquery

    END

Then use above procedure to get the data

you can take a look at: http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure

0
0

If you have few fields to check, you might use something like

"SELECT ProductName, ProductPrice FROM Product 
        WHERE (@type = 'ProductName' and ProductName LIKE '%' + @search + '%')
           OR (@type = 'ProductDescription' and ProductDescription LIKE '%' + @search + '%')
           OR (@type = 'Metadata' and Metadata LIKE '%' + @search + '%')"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.