Alvis Chen
Alvis Chen

Reputation: 47

asp.net SqlDataSource SelectCommand using LIKE with QueryString

<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?

Upvotes: 3

Views: 5014

Answers (2)

Adrian Iftode
Adrian Iftode

Reputation: 15663

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 + '%')"

Upvotes: 0

Thakur
Thakur

Reputation: 2020

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

Upvotes: 2

Related Questions