[英]passing an operand as an sql parameter
我目前正在将asp.net应用程序作为sql server 2008的后端。 我想让用户能够在SQL语句中指定要过滤的内容。 在界面上,我为他们提供了选择以下内容的选项:等于大于小于等
我想将此作为参数传递给要执行的sql查询。 我怎样才能最好地做到这一点?
例如
Select amount, deduction, month from loan where amount @operant 10000;
@operand
是上述下拉列表的返回值,即= < > <= >=
@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..
...
另外,我想说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上的精彩文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.