문제

I want to create a stored procedure in SQL Server 2012 that accepts a phrase as a condition. 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.

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

도움이 되었습니까?

해결책

In this case you need dynamic sql so change sp as per below

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.

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top