将动态SQL的结果转换为sql-server的变量


116

在存储过程中执行动态SQL,如下所示:

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
SET @city = 'London'
SET @sqlCommand = 'SELECT COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

如何在SP中使用count(*)列值作为返回值?

Answers:


202
DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
declare @counts int
SET @city = 'New York'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city, @cnt=@counts OUTPUT
select @counts as Counts

4
+1:您击败了我,需要声明一个变量,并将其标记为OUTPUT。 有关更多信息以及有关SQL Server动态SQL的推荐读物,请参阅动态SQL的诅咒和祝福
OMG Ponies 2010年

1
谢谢。我缺少N'@ city nvarchar(75),@ cnt int OUTPUT'中的OUTPUT关键字。
Peter Lindholm

1
有没有不需要向动态语句添加输出变量的解决方案???
Tab Alleman '16

2

您可能已经尝试过了,但是您的规格是否可以执行此操作?

DECLARE @city varchar(75)
DECLARE @count INT
SET @city = 'London'
SELECT @count = COUNT(*) FROM customers WHERE City = @city

2

动态版本

    ALTER PROCEDURE [dbo].[ReseedTableIdentityCol](@p_table varchar(max))-- RETURNS int
    AS
    BEGIN
        -- Declare the return variable here
       DECLARE @sqlCommand nvarchar(1000)
       DECLARE @maxVal INT
       set @sqlCommand = 'SELECT @maxVal = ISNULL(max(ID),0)+1 from '+@p_table
       EXECUTE sp_executesql @sqlCommand, N'@maxVal int OUTPUT',@maxVal=@maxVal OUTPUT
       DBCC CHECKIDENT(@p_table, RESEED, @maxVal)
    END


exec dbo.ReseedTableIdentityCol @p_table='Junk'

0
DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
DECLARE @cnt int
SET @city = 'London'
SET @sqlCommand = 'SELECT @cnt=COUNT(*) FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
RETURN @cnt

1
我认为您的答案被截断了。
Sage 2010年

讯息137,Must declare the scalar variable "@cnt". 讯息178 、A RETURN statement with a return value cannot be used in this context.. 不错的作品,兄弟))
it3xl

0

这可能是一个解决方案?

declare @step2cmd nvarchar(200)
DECLARE @rcount NUMERIC(18,0)   
set @step2cmd = 'select count(*) from uat.ap.ztscm_protocollo' --+ @nometab
EXECUTE @rcount=sp_executesql @step2cmd
select @rcount

-2
 vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE'' 
    AND OBJECT_NAME  =''' || vTBL_CLIENT_MASTER || '''';
    PRINT_STRING(VMYQUERY);
    EXECUTE IMMEDIATE  vMYQUERY INTO VCOUNTTEMP ;

这不适用于sql server。
罗伯特·卢霍
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.