将动态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

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


繁华开满天机
浏览 510回答 3
3回答

30秒到达战场

DECLARE @sqlCommand nvarchar(1000)DECLARE @city varchar(75)declare @counts intSET @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 OUTPUTselect @counts as Counts

浮云间

您可能已经尝试过了,但是您的规格是否可以执行此操作?DECLARE @city varchar(75)DECLARE @count INTSET @city = 'London'SELECT @count = COUNT(*) FROM customers WHERE City = @city

BIG阳

动态版本    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)    ENDexec dbo.ReseedTableIdentityCol @p_table='Junk'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server