使用动态sql在存储过程中填充临时变量

使用动态sql在存储过程中填充临时变量,sql,sql-server,sql-server-2008,stored-procedures,Sql,Sql Server,Sql Server 2008,Stored Procedures,我有一个存储过程,其中声明了一个int变量,需要使用动态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 @co

我有一个存储过程,其中声明了一个int变量,需要使用动态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

使用
sp_executeSQL
和一个输出参数:

DECLARE @count INT = 1
DECLARE @qry   NVARCHAR(MAX)

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

EXEC sp_executesql @qry, N'@count INT OUTPUT', @count OUTPUT
    
SELECT @count

您可以尝试使用这样的临时表

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)

看起来您已经在
@count
中选择了count(*)的值,那么问题出在哪里?