Question

I want to dynamically build the WHERE clause for my query using string builder.

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];
}
Was it helpful?

Solution

Write a stored Procedure that takes the filter query dynamically according to cases

    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

Also you have to make a test to check if the Parameters provided are empty strings and modify your where clause accordingly. Check Dynamic SQL for more info

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top