SQL LIKE % NOT SEARCHING

最后都变了- 提交于 2020-01-03 17:20:50

问题


I want to perform a simple search using the SQL LIKE function. Unfortunately for some reason , it doesn't seem to be working. Below is my code.

private void gvbind()
{
    connection.Open();
    string sql = "";

    if (txtSearch.Text.Trim() == "")
    {
        sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID ORDER BY a.[clientID]";
    }
    else
    {
        sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID WHERE b.[bname] LIKE '%@search%' ORDER BY a.[clientID]";
    }

    SqlCommand cmd = new SqlCommand(sql,connection);
    cmd.Parameters.AddWithValue("@search", txtSearch.Text.Trim());
    cmd.CommandType = CommandType.Text;
    SqlDataAdapter adp = new SqlDataAdapter();
    adp.SelectCommand = cmd;
    DataSet ds = new DataSet();
    adp.Fill(ds);

    connection.Close();

    if (ds.Tables[0].Rows.Count > 0)
    {
        gvBranch.Enabled = true;
        gvBranch.DataSource = ds;
        gvBranch.DataBind();
    }
    else
    {
        ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
        ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());

        gvBranch.DataSource = ds;
        gvBranch.DataBind();

        int columncount = gvBranch.Rows[0].Cells.Count;
        gvBranch.Rows[0].Cells.Clear();
        gvBranch.Rows[0].Cells.Add(new TableCell());
        gvBranch.Rows[0].Cells[0].ColumnSpan = columncount;
        gvBranch.Rows[0].Cells[0].Text = "No Records Found";
    }
    ds.Dispose();
}

the above method is called in the Page_Load() method using

if((!Page.IsPostBack))
{
    gvBind();
}

it is called on button search click aslo. However, it return No record found when ever i perform the search.


回答1:


Use

LIKE '%' + @search + '%'

instead of

LIKE '%@search%'

Full query;

...
else
{
    sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID WHERE b.[bname] LIKE '%' + @search + '%' ORDER BY a.[clientID]";
}

And actually, you don't need to use square brackets ([]) every column in your query. Use them if your identifiers or object names are a reserved keyword.

Thanks. It works , but any explanation for that?

The main problem is here, your query parameter is inside quotes. In quotes, SQL Server will recognize it as a string literal and never sees it as a parameter.



来源:https://stackoverflow.com/questions/18630575/sql-like-not-searching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!