我有一个存储过程,我声明一个需要使用动态sql填充的int变量
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 :(得分:4)
使用sp_executeSQL
和输出参数:
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
答案 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)