الاثنين، 12 ديسمبر 2011

How do I code the Stored Procedure and the parameter to it to use the LIKE operator?


How do I code the Stored Procedure and the parameter to it to use the LIKE operator? 

The answer should seem quite simple, but it is not exactly as you would do it in dynamic sql.  It is almost the same with a subtile difference.

In dynamic sql, you might do something like this:
string searchText = "register";string sql = "select * from FAQs where QuestionColumn LIKE '%" +
                    searchText + 
"%'";

to create the dynamic sql statement, and it will work fine.  However, it does not appear that passing a parameter value like the following code works in the Stored Procedure; at least it failed to make a find for me, even though I had copied the code from VBScript in an old ASP page, where it was working. 
    string searchString = "'%register%'";

    sqlCommand.Parameters.Add(
new SqlParameter("@SearchString",
        
SqlDbType.VarChar, 50));
    sqlCommand.Parameters[0].Value = searchString;


and the code in the stored procedure was:

    SELECT Question, Answer     FROM SP_FAQs     WHERE Question LIKE @SearchString OR
          Answer 
LIKE @SearchString 

So, to get it to work, I changed the parameter setting code to:
    string searchString = "register";

    sqlCommand.Parameters.Add(
new SqlParameter("@SearchString",
        
SqlDbType.VarChar, 50));
    sqlCommand.Parameters[0].Value = searchString;

and the Stored Procedure code to the following:
    SELECT Question, Answer     FROM SP_FAQs     WHERE Question LIKE '%' + @SearchString + '%' OR
          Answer 
LIKE '%' + @SearchString + '%'

The subtile difference is that the adding of the "%" to the beginning and end of the parameter is done inside the Stored Procedure instead of passing it in with the parameter.  Even if somehow I made a simple mistatke that was causing the search to fail, it is still better to have the stored procedure do the work of enclosing the searchString in "%" than for each call have to worry about passing in anything but the actual text for which to search.

ليست هناك تعليقات:

إرسال تعليق