将操作数作为sql参数传递

我目前正在开发一个以sql server 2008作为后端的asp.net应用程序。 我想让用户能够在SQL语句中指定他们想要过滤的内容。 在界面上,我给他们选择以下选项作为下拉列表:等于大于小于等

我想将此作为参数传递给要执行的sql查询。 我怎样才能做到最好?

例如;

Select amount, deduction, month from loan where amount @operant 10000; 

@operand是上述下拉列表的返回值,即= = @operand = =

假设所有正整数<20亿,此解决方案避免了多个查询和动态SQL。 OPTION (RECOMPILE)有助于阻止参数嗅探,但这可能不是必需的,具体取决于表的大小,参数化设置和“针对ad hoc工作负载优化”设置。

 WHERE [Amount] BETWEEN CASE WHEN @operand LIKE '<%' THEN 0 WHEN @operand = '>' THEN @operant + 1 ELSE @operant END AND CASE WHEN @operand LIKE '>%' THEN 2147483647 WHEN @operand = '<' THEN @operant - 1 ELSE @operant END OPTION (RECOMPILE); 

我会写几个“IF”语句。 代码不是很短,但应该很快。

 IF(@operand = '=') Select.. ELSE IF(@operand = '>=') Select.. ... 

另外,我会说,Top(@someRowCount)可能是个好主意。

您需要动态SQL用于此方案

对于你的例子,这可以

 DECLARE @sql AS nvarchar(max) -- Use max if you can, if you set -- this to a specific size then your assignment later can be -- truncated when maintained and still be valid. SET @sql = 'Select amount, deduction, month from dbo.loan where amount ' + @operand + ' 10000' EXEC sp_executesql @sql 

更新1

有两种方法可以执行动态sql:Exec()和sp_executesql

阅读注释为什么首选sp_executesql(仍然要小心sql注入!)

我还在表格前加上dbo,以便可以在不同用户之间缓存执行计划

更多信息,请参阅http://www.sommarskog.se/dynamic_sql.html#queryplans上的精彩论文