我有一个C#表单,有6个过滤器(5个组合框和1个文本框),用户可以用它来执行搜索。问题是用户可以将一些留空或全部使用。要进行过滤搜索,我在执行SELECT查询时使用AND,但问题是当某些过滤器为空时,它将返回空白或空搜索。如果我将每个条件作为一个查询,我将有大约700左右的查询。所以我想在这个链接中搜索壁橱
Ignore empty textboxes while searching in database
using (SqlConnection conn = new SqlConnection(@"Data Source=(local);
Initial Catalog=inventory;
Integrated Security=True"))
{
conn.Open();
string query = "SELECT * FROM [dbo].[product] WHERE IsDeleted = '0'";
using (SqlCommand scmd = new SqlCommand())
{
if (!string.IsNullOrEmpty(cmbItem.Text))
{
query += " AND Item Like @Item";
scmd.Parameters.Add("@Item", SqlDbType.VarChar).Value = "%" + item + "%";
}
}
if (!string.IsNullOrEmpty(cmbBrand.Text))
{
query += " AND Brand Like @Brand";
scmd.Parameters.Add("@Brand", SqlDbType.VarChar).Value = "%" + brand + "%";
}
//...additional query
}
scmd.CommandText = query;
scmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(scmd))
{
dataGridView1.Refresh();
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
conn.Close();
}
执行搜索时,会出现这样的错误;
'列名无效' IsNull'。'
我的原始查询是这样的。但如果其中一个where条件为空/空,则不会选择任何内容。
SELECT * FROM [dbo].[product] WHERE Item = '" + item + "'
AND Brand = '" + brand + "'
AND Description = '" +desc + "'
AND Manufacturer = '" + manu + "'
AND Car = '" + car + "'
AND Year = '" + year + "'
如果我使用OR而不是AND。它会选择这样的东西。
以下是理想搜索的图片。
解决,改变IsDeleted =' 0'到1 = 1
string query = @"SELECT * FROM[dbo].[product] WHERE 1=1";
答案 0 :(得分:0)
您可以使用存储过程并将参数设置为默认值
样品:
float pad;
当文本框为空或未选择下拉列表时,获取所有记录
答案 1 :(得分:0)
您原来的if /和条件应该有效,但您可能遇到的是表COLUMN与PARAMETER的错误解析。因为你有
的例子Item like @Item
如果没有实际参数Item,则SQL暗示使用自己的值。对于这些类型的查询,我尝试将参数名称作为匹配前缀。改为
Item like @parmItem
显然更改参数名称字符串以匹配“@parmItem”引用。这样,SQL引擎正在寻找的价值没有任何歧义。