已在数据库中创建以下存储过程,该存储过程在数据库中正常工作:
create procedure [dbo].[search_pazhoheshgar]
@se_code_melli varchar(10) = NULL,
@se_name nvarchar(30) = NULL,
@se_family nvarchar(30) = NULL,
@se_name_uni nvarchar(100) = NULL,
@se_name_reshte_tahsili nvarchar(50) = NULL
AS
begin try
begin tran
SET NOCOUNT ON;
select sabt.code_melli, sabt.name, sabt.family, sabt_como_univercity.name_uni,
sabt_como_reshte.name_reshte_tahsili
from sabt
inner join sabt_como_univercity ON sabt.univercity = sabt_como_univercity.id_uni
inner join sabt_como_reshte ON sabt.name_reshte = sabt_como_reshte.id_reshte_tahsili
where
sabt.code_melli like '%' + @se_code_melli + '%' or
sabt.name like '%' + @se_name + '%' or
sabt.family like '%' + @se_family + '%' or
sabt_como_univercity.name_uni like '%' + @se_name_uni + '%' or
sabt_como_reshte.name_reshte_tahsili like '%' + @se_name_reshte_tahsili + '%'
commit tran
end try
begin catch
rollback tran
return -1
end catch
使用以下命令,我想从C#程序运行存储过程:
SqlParameter[] sqlParams;
string sqlQuery;
sqlQuery = "search_pazhoheshgar @se_code_melli, @se_name, @se_family, @se_name_uni, @se_name_reshte_tahsili";
sqlParams = new SqlParameter[]
{
new SqlParameter { ParameterName = "@se_code_melli", Value = (object)textBox23.Text ?? DBNull.Value},
new SqlParameter { ParameterName = "@se_name", Value = (object)textBox22.Text ?? DBNull.Value},
new SqlParameter { ParameterName = "@se_family", Value = (object)textBox21.Text ?? DBNull.Value},
new SqlParameter { ParameterName = "@se_name_uni", Value = (object)comboBox11.Text ?? DBNull.Value},
new SqlParameter { ParameterName = "@se_name_reshte_tahsili", Value = (object)comboBox12.Text ?? DBNull.Value}
};
using (SamenEntities dbContext = new SamenEntities())
{
dataGridView1.DataSource = dbContext.Database.SqlQuery<search_pazhoheshgar_Result>(sqlQuery, sqlParams).ToList();
}
但是运行后,所有现有行都从数据库中显示。另外,我使用以下方式来运行存储过程。但是再次显示所有行:
using (SamenEntities dbContext = new SamenEntities())
{
dataGridView1.DataSource = dbContext.search_pazhoheshgar(textBox23.Text, textBox22.Text, textBox21.Text, comboBox11.Text, comboBox12.Text);
}
如何解决搜索者问题?
答案 0 :(得分:2)
您的查询将对搜索条件的检查与OR
条件结合在一起。这意味着,当只有一个条目为空字符串时,您将获得整个结果集(除非相应列为NULL
)。
您的表达式Value = (object)textBox23.Text ?? DBNull.Value
将永远不会产生DBNull
,因为TextBox.Text
将具有值""
而不是null
。因此,您将向您的存储过程传递一个空字符串,这将导致...
abt.code_melli LIKE '%' + @se_code_melli + '%'
...评估为...
abt.code_melli LIKE '%%'
无论其他参数是什么(因为它们与NULL
组合在一起),这都会产生整个结果集(除非该列包含OR
值)。
在WHERE
状态下,您必须防止出现这种情况:
--[...]
WHERE
@se_code_melli IS NOT NULL AND @se_code_melli <> '' AND
sabt.code_melli LIKE '%' + @se_code_melli + '%' OR
@se_name IS NOT NULL AND @se_name <> '' AND sabt.name LIKE '%' + @se_name + '%' OR
--[...]