我見過很多關於在Sql查詢和「like」中使用參數的問題,但我嘗試了所有我已經看到的編碼方式,但仍然無法獲得我的查詢結果。如果我在查詢本身中放置一個值,它運行良好。當我運行列出的第一個查詢時,出現錯誤「必須聲明標量變量」@Search「,但我認爲我是通過cmd.Parameters.AddWithValue語句來做到的。任何人都可以看到我可能做錯了什麼? 。獲取查詢以處理參數和「like」
//Declare the connection object
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
//Connect to the db
Conn.Open();
//Define query
//This query doesn't work
string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer WHERE (State LIKE '%' + @Search + '%')";
//This query doesn't work either
string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer WHERE State LIKE @Search";
//This query works
string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer WHERE State LIKE 'MI'";
//Declare the Command
SqlCommand cmd = new SqlCommand(sql, Conn);
//Add the parameters needed for the SQL query
cmd.Parameters.AddWithValue("@Search", "%" + txtSearch.Text + "%");
//Declare a SQL Adapter
SqlDataAdapter da = new SqlDataAdapter(sql, Conn);
//Declare a DataTable
DataTable dt = new DataTable();
//Populate the DataTable
da.Fill(dt);
//Bind the Listview
lv.DataSource = dt;
lv.DataBind();
dt.Dispose();
da.Dispose();
Conn.Close();
http://stackoverflow.com/questions/251276/howto-parameters-and-like-statement-sql –
您正在使用什麼數據庫? –
@rontornambe:這是SQL Server。 –