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);
上面的命令有什麼問題? 我收到「@astr附近」錯誤消息。SQL命令搜索
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);
上面的命令有什麼問題? 我收到「@astr附近」錯誤消息。SQL命令搜索
您必須指定在變量野生字符(%
),在查詢中刪除野生字符。
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);
大約有您的搜索字符串引號失蹤,一個括號太多:
SqlCommand cmd = new SqlCommand(
@"select * from [Table]
where Col1 like '%' || @astr || '%'
or Col2 like '%' || @astr || '%'
or Col3 like '%' || @astr || '%'", con);
是|| ? 我從來沒有在SQL查詢中看到過這個 – user3688221
它是連接字符串的標準SQL操作符,例如''你好'|| 「world''。幾乎所有的DBMS都支持這種語法。但也有例外。我認爲SQL Server使用非標準的'+'作爲例子。而在MySQL中,它可能取決於某些設置,可能需要使用'CONCAT'。 –
如果而aStr是一個字符串。你可以試試這個。
string astr = "ABC";
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);
嘗試在您的sql查詢中刪除'''末尾,使用'like%@ astr%' –
哦!謝謝! 3小時,我甚至不知道它 – user3688221
沒有後顧之憂,發生在繁忙的一天:-) –