将动态 SQL 的结果放入 SQL-server 的变量中

在存储过程中执行动态 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

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

197527 次浏览

您可能已经尝试过这种方法,但是您的规范是否允许您这样做呢?

DECLARE @city varchar(75)
DECLARE @count INT
SET @city = 'London'
SELECT @count = COUNT(*) FROM customers WHERE City = @city
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
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @count INT
DECLARE @city VARCHAR(75)
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 = @count OUTPUT


SELECT @count
 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 ;

动态版本

    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'

这能解决问题吗?

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