我会写这样的东西:
create procedure usp_search (
@param1 varchar(50) = null
,@param2 carchar(50) = null
) as
begin
select field1
,field2
,field3
,fieldN
from table t with(nolock)
where ((@param1 is null) or (t.fieldX == @param1))
and ((@param2 is null) or (t.fieldY == @param2))
end
然后在你的客户上你喜欢
//code
var connection = new SqlConnection("connection_string");
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = "usp_Search";
command.CommandType = CommandType.StoredProcedure;
if((string.IsNullOrEmpty(stringVariable1)) || (stringVariable2.ToLower().Equals("any"))) {
command.Parameters.Add("@param1", SqlType.VarChar, 50).Value = DBNull.Value;
} else {
command.Parameters.Add("@param1", SqlType.VarChar, 50).Value = stringVariable1;
}
if((string.IsNullOrEmpty(stringVariable2)) || (stringVariable2.ToLower().Equals("any"))) {
command.Parameters.Add("@param2", SqlType.VarChar, 50).Value = DBNull.Value;
} else {
command.Parameters.Add("@param2", SqlType.VarChar, 50).Value = stringVariable2;
}
// code
沿着这些思路......这样您的搜索查询可以检索过滤或未过滤的结果......当然,您必须注意此类查询的一些陷阱
编辑:仅在 C# 代码中完成的相同操作将是这样的:
var sb = new StringBuilder();
sb.Append("select field1 ,field2, field3, fieldN ");
sb.Append("from table t with(nolock) ");
sb.Append("where ((@param1 is null) or (t.fieldX == @param1))");
sb.Append("and ((@param2 is null) or (t.fieldY == @param2))");
var connection = new SqlConnection("connection_string");
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = sb.ToString();
command.CommandType = CommandType.Text;
if((string.IsNullOrEmpty(stringVariable1)) || (stringVariable2.ToLower().Equals("any"))) {
command.Parameters.Add("@param1", SqlType.VarChar, 50).Value = DBNull.Value;
} else {
command.Parameters.Add("@param1", SqlType.VarChar, 50).Value = stringVariable1;
}
if((string.IsNullOrEmpty(stringVariable2)) || (stringVariable2.ToLower().Equals("any"))) {
command.Parameters.Add("@param2", SqlType.VarChar, 50).Value = DBNull.Value;
} else {
command.Parameters.Add("@param2", SqlType.VarChar, 50).Value = stringVariable2;
}