SQL LIKE表达式给出空结果

时间:2019-03-14 06:29:22

标签: c# sql sql-server sql-like

似乎使用Like需要一些确切的格式,我不知道。 这是代码:

private void DoFilter()
{
    using (connection = new SqlConnection(connectionString))
    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customers WHERE CompanyName = @filter + '%'", connection))
    {
        adapter.SelectCommand.Parameters.AddWithValue("@filter", txtFilter.Text.Trim());

        DataTable TCustomers = new DataTable();
        adapter.Fill(TCustomers);

        lstCustomers.DisplayMember = "CompanyName";
        lstCustomers.ValueMember = "Id";
        lstCustomers.DataSource = TCustomers;

    }
}

该代码未引发任何错误。它只是使ListBox(lstCustomers)为空。 (txtFilter是一个TextBox,其中包含过滤器字符串)。

3 个答案:

答案 0 :(得分:4)

使用like operator代替=

SELECT * FROM Customers WHERE CompanyName like @filter + '%'"

答案 1 :(得分:0)

您没有使用LIKE运算符,而是使用了=运算符。

应为:

using (SqlDataAdapter adapter = new SqlDataAdapter(
    "SELECT * FROM Customers WHERE CompanyName LIKE @filter + '%'", connection))

SQL的编写方式与末尾的%完全匹配,因此不会得到任何结果。

答案 2 :(得分:0)

“赞”应用作(SELECT * FROM Customer WHERE CompanyName LIKE @filter +'%'):

private void DoFilter()
{
    using (connection = new SqlConnection(connectionString))
    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customers WHERE CompanyName LIKE @filter + '%'", connection))
    {
        adapter.SelectCommand.Parameters.AddWithValue("@filter", txtFilter.Text.Trim());

        DataTable TCustomers = new DataTable();
        adapter.Fill(TCustomers);

        lstCustomers.DisplayMember = "CompanyName";
        lstCustomers.ValueMember = "Id";
        lstCustomers.DataSource = TCustomers;

    }
}