T-SQL 将动态SQL的结果集赋值到变量

时间:2023-03-09 14:43:55
T-SQL 将动态SQL的结果集赋值到变量

1. 使用输出变量

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

2. 使用临时表

DECLARE @sqlCommand nvarchar(1000)
DECLARE @city varchar(75)
SET @city = 'New York'
SET @sqlCommand = 'SELECT COUNT(*) as count into #temp FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75),@cnt int OUTPUT', @city = @city
SELECT @counts = count from #temp