c#sql"喜欢"手术

时间:2017-12-01 16:56:51

标签: c# sql sql-like

如何更换" @ something"使用" textBox2.Text"那么sql可以搜索包含它的东西吗?这不起作用。

private void cmd1_Click(object sender, EventArgs e)
{
    string content = null;
    FbConnection conn = new FbConnection(connectionString);
    conn.Open();
    FbCommand command = conn.CreateCommand();

    command.CommandText = @"select a.NAME, a.SCHOOL, a.CLASS
    from PEOPLE a, PLACES b
    where 
    b.KEY=a.PLACE and          
    a.SCHOOL like '%@something%'
    order by a.NAME";

    command.Parameters.AddWithValue("@something", textBox2.Text);
    FbDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        content += (string)reader["NAME"] + "\r\n";
        textBox1.Text = content;
    }
}

2 个答案:

答案 0 :(得分:7)

通过在SQL语句中将@something包装在单引号中,您告诉数据库将其视为直接字符串值,以便搜索将匹配记录与实际的"%@ something%& #34; string - 具有"%"的逻辑部分,当然。

a.SCHOOL like @something

...

command.Parameters.AddWithValue("@something", "%" + textBox2.Text + "%");

答案 1 :(得分:0)

或者使用此解决方案。

command.CommandText = @"select a.NAME, a.SCHOOL, a.CLASS
from PEOPLE a, PLACES b
where 
b.KEY=a.PLACE and          
a.SCHOOL like '%' || @something || '%'
order by a.NAME";

command.Parameters.AddWithValue("@something", textBox2.Text);

像igor一样,%@something%是一个字符串。您可以将@something变为'变量'并在SQL查询内部之前和之后连接%

更新:首先使用+(Microsoft SQL Server)连接它,但@hvd表示firebird使用||。所以我改变了它。