user3688221 user3688221 - 7 months ago 17
SQL Question

SQL command search

SqlCommand cmd = new SqlCommand("select * from [Table] where Col1 like
%@astr% or Col2 like %@astr% or Col3 like %@astr%)", con);
cmd.Parameters.AddWithValue("@astr", st);


What is wrong with the command above?
I got error message "near the @astr".

Answer

You have to specify wild characters (%) in your variable, remove wild characters in query.

st = string.Format("%{0}%", st); // in case your search string don't have wild characters..
SqlCommand cmd = new SqlCommand("select * from [Table] where Col1 like 
                      %@astr% or Col2 like @astr or Col3 like @astr)", con);        
cmd.Parameters.AddWithValue("@astr", st);
Comments