如何处理动态sql参数

处理动态sql参数的好方法是什么?

我有一个搜索表单,其中包含一大堆不同的搜索参数。 如果参数为空并且我在sql字符串中有参数,那么它会阻塞或减慢查询?

根据具体实现,我们有两个解决此问题的一般方法:

1)在代码中动态构建SQL查询的filter语句,跳过任何空的参数。 如果允许用户为单个列选择多个值(即选择50个状态中的0个或更多个来过滤数据),这是最佳方法。

例如:

假设txtCondition1和txtCondition2是文本框:

  // Assuming conn is an open SqlConnection System.Text.StringBuilder sbSQL = new StringBuilder(500); List cParameters = new List(); // Add a default condition of 1=1 so that all subsequent conditions can be added // with AND instead of having to check to see whether or not any other conditions // were added before adding AND. sbSQL.Append("SELECT * FROM MyTestTable WHERE 1 = 1 "); if (!String.IsNullOrEmpty(txtCondition1.Text)) { sbSQL.Append(" AND Column1 = @Column1"); cParameters.Add(new SqlParameter("@Column1", txtCondition1.Text)); } if (!String.IsNullOrEmpty(txtCondition1.Text)) { sbSQL.Append(" AND Column2 = @Column2"); cParameters.Add(new SqlParameter("@Column2", txtCondition2.Text)); } SqlCommand oCommand = new SqlCommand(sbSQL.ToString, conn); if (cParameters.Count != 0) { oCommand.Parameters.AddRange(cParameters.ToArray()); } // Do something with oCommand 

2)如果值受到更多约束,我们通常会将它们传递给存储过程,该过程负责通过测试“空白”参数来确定是否要评估该值,null,空字符串,0表示数字等

可以做的一件事是检查参数是否已传递给存储过程。 你可以这样做:

 create procedure my_procedure ( @param1 as int = null @param2 as int = null ) as begin select field1, field2, fieldn from table where ((@param1 is null) or (field2 = @param1)) and ((@param2 is null) or (field2 = @param2)) end 

我宁愿在sql程序上执行此操作而不是在应用程序中执行此操作