我想使用字符串生成器动态查询WHERE子句

时间:2014-02-10 05:58:37

标签: c# sql-server ado.net stringbuilder

我想使用字符串构建器为我的查询动态构建WHERE子句。

private void btnquery_Click(object sender, EventArgs e)
{
    StringBuilder strQuery = new StringBuilder();
    StringBuilder strWhereClass = new StringBuilder();
    strQuery.Append("SELECT * FROM [dbo].[poi5] ");

    if (namecb.Checked)
    {
        if (string.IsNullOrEmpty(nametxt.Text))
        {   MessageBox.Show("Please enter the name!!!");
            nametxt.Focus();
            return;
        } 
        else
        {
            if (strWhereClass.Length == 0)
            { strWhereClass.Append("WHERE [Name_POI] ='" + nametxt.Text + "';");
            } else{ trWhereClass.Append(" AND [Name_POI]] ='" + nametxt.Text + "';");
            }
        }
    }

    if (versioncb.Checked)
    {
        if (string.IsNullOrEmpty(versiontxt.Text))
        {  MessageBox.Show("Please enter the version!!!");
            versiontxt.Focus();
            return;
        }
        else
        { 
            if (strWhereClass.Length == 0) 
            {
                strWhereClass.Append("WHERE [Version] = '" versiontxt.Text + "'");
            } 
            else 
            {
                strWhereClass.Append(" AND [Version] = '" + versiontxt.Text + "'");
            }               
        }
    }

    con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=POIFINALLY;Integrated Security=True;");

    cmd = new SqlCommand(strQuery.ToString() + strWhereClass.ToString(), con);
    con.Open();
    da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
}

1 个答案:

答案 0 :(得分:1)

编写一个存储过程,根据案例

动态获取过滤器查询
    Create procedure GetPoi (@Name nvarchar (100),@Version nvarchar (100))
    as 
    begin
    declare @Command nvarchar(max)
    set @Command = 'select * from tablename where name ='''+@Name+''' and Version='''+@Version+''''
    exec sp_executeSql @Command
    end

此外,您还必须进行测试以检查提供的参数是否为空字符串并相应地修改您的where子句。 检查动态SQL以获取更多信息