如何在t-sql中使用'execute'来设置variables的值?

DECLARE @dbName nvarchar(128) = 'myDb' DECLARE @siteId int exec ('SELECT TOP 1 @siteId = Id FROM ' + @dbName + '..myTbl') select @siteId 

当我运行上面的脚本时,出现以下错误

 Msg 137, Level 15, State 1, Line 1 Must declare the scalar variable "@siteId". (1 row(s) affected) 

为什么以及如何解决它?

谢谢

您可以将输出参数与sp_executesql一起使用。

 DECLARE @dbName nvarchar(128) = 'myDb' DECLARE @siteId int DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @siteId = Id FROM ' + quotename(@dbName) + N'..myTbl' exec sp_executesql @SQL, N'@siteId int out', @siteId out select @siteId 

dynamicSQL与外部调用SQL的范围不同,因此不能识别@siteid

您将不得不在dynamicSQL之外使用临时表/表variables:

 DECLARE @dbName nvarchar(128) = 'myDb' DECLARE @siteId TABLE (siteid int) INSERT @siteId exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl') select * FROM @siteId 

注意:没有ORDER BY的TOP是毫无意义的 。 表格没有自然的,隐含的或内在的顺序。 任何订单只能由最外面的ORDER BY保证

 SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Andrew Foster -- Create date: 28 Mar 2013 -- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table -- ============================================= ALTER PROCEDURE dbo.PullTableColumn ( @columnName varchar(255), @id int ) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @columnVal TABLE (columnVal nvarchar(255)); DECLARE @sql nvarchar(max); SET @sql = 'SELECT ' + @columnName + ' FROM regUsers WHERE id=' + CAST(@id AS varchar(10)); INSERT @columnVal EXEC sp_executesql @sql; SELECT * FROM @columnVal; END GO