简体   繁体   English

将操作数作为sql参数传递

[英]passing an operand as an sql parameter

I am currently working on an asp.net application that has sql server 2008 as its backend. 我目前正在将asp.net应用程序作为sql server 2008的后端。 I want to give the user the ability to specify what they want to filter by on the SQL statement. 我想让用户能够在SQL语句中指定要过滤的内容。 On the interface I am giving them the option to select the following as a dropdown: equals to greater than Less than etc 在界面上,我为他们提供了选择以下内容的选项:等于大于小于等

I want to pass this as a parameter on the sql query to be executed. 我想将此作为参数传递给要执行的sql查询。 How best can I achieve this? 我怎样才能最好地做到这一点?

for eg; 例如

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

the @operand is the return values of the above dropdown which is = < > <= >= @operand是上述下拉列表的返回值,即= < > <= >= @operand = < > <= >=

Assuming all positive integers < 2 billion, this solution avoids multiple queries and dynamic SQL. 假设所有正整数均小于20亿,则此解决方案避免了多个查询和动态SQL。 OPTION (RECOMPILE) helps thwart parameter sniffing, but this may not be necessary depending on the size of the table, your parameterization settings and your "optimize for ad hoc workload" setting. 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);

I would write few "IF" statements. 我会写一些“ IF”语句。 Code is not very short, but should be fast. 代码不是很短,但是应该很快。

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

Also, i would say, that Top (@someRowCount) could be great idea. 另外,我想说Top(@someRowCount)可能是个好主意。

You need dynamic sql for this scenario 在这种情况下,您需要动态sql

For your example this can be 以您的示例为例

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

Update 1 更新1

There are 2 ways to execute dynamic sql : Exec() and sp_executesql 有两种执行动态sql的方法:Exec()和sp_executesql

Read the comments why sp_executesql is preferred (still, beware of sql injections!) 阅读注释,为什么首选sp_executesql(仍然要注意sql注入!)

I also prefix the table with the dbo so that the execution plan can be cached between different users 我还用dbo前缀表,以便可以在不同用户之间缓存执行计划

More info in the awesome paper at http://www.sommarskog.se/dynamic_sql.html#queryplans 有关更多信息, 请参见http://www.sommarskog.se/dynamic_sql.html#queryplans上的精彩文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM