将操作数作为 SQL 参数传递



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

我想将其作为要执行的 sql 查询的参数传递。我怎样才能最好地实现这一目标?

例如;

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

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

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

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..
...

另外,我想说,顶部(@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 的精彩论文

最新更新