TSQL - Trying to use variable with IF EXISTS() Fun

2019-02-25 12:55发布

问题:

Our company runs a MS Access Frontend and SQL Backend, and I'm trying to provide a stored procedure for the frontend that would allow it to have access to T-SQL's IF EXIST, instead of using DCount to improve performance. To do this I need to be able to pass the SELECT statement to the stored procedure, and so far I have the following code:

CREATE PROCEDURE [dbo].IfExists 
@selectStatement varchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (@selectStatement)
    RETURN 1
ELSE
    RETURN 0
END
GO

which doesn't work because it doesn't like the @selectStatement instead of a hardcoded statement. Not sure how I can do this, any help would be appreciated.

回答1:

You need to use dynamic sql to achieve this

http://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

e.g.:

DECLARE @DynamicSQl NVARCHAR(MAX), @retVal INT

SET @DynamicSQl = 'select @retVal = 1 from (' + @selectCommand + ') t'

EXEC sp_executesql @DynamicSQl, N'@retVal INT OUTPUT', @retVal output

IF (@retVal = 1)
  RETURN 1
ELSE
  RETURN 0