0

Can't get this working, how to add a parameter in SQL LIKE % % when its type is char?

SQL.Append("(Code LIKE @Code)");
var sqlParameter = new SqlParameter("@Code",
                      System.Data.SqlDbType.Char, 
                      10,
                      System.Data.ParameterDirection.Input,
                      true, 
                      0, 
                      0, 
                      "Code", 
                      System.Data.DataRowVersion.Current, 
                      "'%300%'");    
2
  • Do you have any error message? Commented Apr 20, 2015 at 14:41
  • No error message, the query just doesn't return anything with a parameter. But with dynamic SQL it works (Code LIKE '%300%') Commented Apr 20, 2015 at 14:46

2 Answers 2

2

There are two things wrong with your code, the first Soner pointed out, you need to remove the single quotes from your string. The second is the fact that you are using System.Data.SqlDbType.Char as the datatype and passed in a size of 10 to the constructor. This will pad out 10 spaces at the end of your string, effectively turning your string in to "'%300%' "

Use SqlDbType.VarChar instead. Also you don't need all those parameters in the constructor, just fill in the 3 you need then use the .Value property of the parameter you created.

SQL.Append("(Code LIKE @Code)");
var sqlParameter = new SqlParameter("@Code", SqlDbType.VarChar, 10);
sqlParameter.Value = "%300%";

Also, another trick that may be useful to you. If you want to always put the % on both sides but don't want the user to have to provide them you can put them in your query and still use parameters.

string code = "300";

SQL.Append("(Code LIKE '%' + @Code + '%')");
var sqlParameter = new SqlParameter("@Code", SqlDbType.VarChar, 10);
sqlParameter.Value = code;
Sign up to request clarification or add additional context in comments.

1 Comment

Big thanks! With the SqlDbType.VarChar it worked like a charm.
1

Try to use your parameter value without single quotes. I think they make your value part as a string literal instead of parameter.

"%300%"

2 Comments

@Soner I think the problem also comes from the fact that he is using SqlDbType.Char and it is padding his string with spaces which the like is searching for.
@ScottChamberlain Exactly, that was my second thought. If you looking for 300 in your column, sounds like you should not choose Char type at all.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.