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
문제
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