简体   繁体   English

存储过程SQL Server中的表达式

[英]Expression in stored procedure sql server

I want to create a stored procedure in SQL Server 2012 that accepts a phrase as a condition. 我想在SQL Server 2012中创建一个存储过程,该存储过程接受短语作为条件。 I am writing reports that send parameters dynamically. 我正在编写动态发送参数的报告。

The procedure has be something like the following where the variable @WHERE needs to be replaced with the string I send as input. 该过程类似于以下内容,其中变量@WHERE需要替换为我作为输入发送的字符串。

CREATE PROCEDURE [dbo].[TEST] 
    @WHERE NVARCHAR(200)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * FROM MTRL WHERE @WHERE
END

So execution has to be something like 所以执行必须像

execute TEST 'AND PRODUCT=3 AND DATE IS NULL'

I do not want to be explicit with variables. 我不想明确使用变量。 For example, to use 例如,使用

WHERE PRODUCT=@PRODUCT AND DATE = @DATE AND NAME LIKE '%@NAME' 

as this is subject to change. 因为这可能会改变。 Filters are multiple and different every time for the same report according to user selections. 根据用户的选择,相同报告的过滤器每次都不同。

The error I get when I try the generic solution is 我尝试通用解决方案时遇到的错误是

An expression of non-boolean type specified in a context where a condition is expected, near 'END'. 在需要条件的上下文中指定的非布尔类型的表达式,靠近'END'。

In this case you need dynamic sql so change sp as per below 在这种情况下,您需要动态sql,因此请按以下方式更改sp

CREATE PROCEDURE [dbo].[TEST] 
   @WHERE NVARCHAR(200)
AS
BEGIN
SET NOCOUNT ON;
    exec('SELECT * FROM MTRL WHERE 1= 1 ' + @WHERE)
END

It is not advisable to have conditions appended dynamically to where clause, because you will become vulnerable to SQL injection attack. 不建议将条件动态附加到where子句中,因为您将容易受到SQL注入攻击。

But if it is required you can try as following: 但是,如果需要,您可以尝试以下操作:

declare @sql nvarchar(500)
set @sql='SELECT * FROM MTRL WHERE'+ @WHERE
execute sp_executesql @sql

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

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