2014-02-27 35 views
1

我其中我聲明,需要使用動態SQL填充臨時變量使用動態SQL

CREATE PROCEDURE USP_aTABLE_ADD 
/* 

    stored procedure variables 

*/ 
AS 

    DECLARE @count int 
    SET @count = 1 
    DECLARE @qry nvarchar(max) 

/* 
    SET UP @qry which will look like this 
    SELECT @count = count(*) FROM aTABLE WHERE (col1 = 'val1' AND col2 = 'val2'...) 
*/ 


/* 
    How to get the value of @count so that I can continue with add process 
*/ 

IF @count = 0 
BEGIN 
    /*add logic*/ 
END 
+0

作品看起來像你ALRE ady將count(*)的值選擇到'@ count'中,那麼問題是什麼? – Gareth

回答

4

使用sp_executeSQL和輸出參數來填充一個int變量的存儲過程:

DECLARE @count int 
SET @count = 1 
DECLARE @qry nvarchar(max) 

set @qry = N'set @count = (....)' 

exec sp_executesql @qry, N'@count int OUTPUT', @count OUTPUT 

select @count 
+0

+1這個很不錯 –

1

你可以試着和一個臨時表像這樣

DECLARE @tmp TABLE(cnt INT) 
DECLARE @qry nvarchar(max) 

-- Insert the count returned by dynamic SQL into temp table 
SET @qry = 'SELECT COUNT(*) FROM Table WHERE condition' 
INSERT INTO @tmp EXEC(@qry) 

DECLARE @count INT 
SET @count = (SELECT TOP 1 cnd FROM @tmp)