0

我正在 T-SQL 中处理一些相当长且复杂的过程,我需要在查询中使用相当多的变量。

我被困在这样的事情上:

SELECT @TableSQL = 'SELECT ' 
                   + @columnsForInsert 
                   + '= COALESCE(@columnsForInsert 
                   + ''], ['', '''') 
                   + name 
FROM MIGRATION_DICTIONARIES.dbo.' + @TableName + '_COLUMNS '
EXEC sp_executesql @TableSQL
PRINT @columnsForInsert 

如您所见,我尝试将某个临时表中的所有行连接成一行,然后将其分配给@columnsForInsert变量。但是,当我运行此字符串时,sp_executesql它会进入@columnsForInsert不可见的范围。

你们知道如何让它运行吗?

换句话说。我有类似的东西

SELECT @columnsForInsert = COALESCE(@columnsForInsert + '], [', '') + name 
FROM MIGRATION_DICTIONARIES.dbo.Foobar_COLUMNS

这在我的程序中运行良好。然而,在最终版本中,Foobar 将在一个变量中,所以简单地放在@tableName那里是行不通的。我怎样才能做到这一点?

我正在使用 Microsoft SQL Server 2012

4

1 回答 1

0

Here is an example of how to capture output from sp_executesql

http://support.microsoft.com/kb/262499

Although I have never done it, it implies that the below syntax might work to retrieve your variable value from your sp_executesql (assuming all the quotes are in the right place and your syntax is correct)

DECLARE @columnsForInsertOUT VARCHAR(400)
DECLARE @columnsForInsert    VARCHAR(400)
DECLARE @ParmDefinition      VARCHAR(50)
DECLARE @TableSQL            VARCHAR(200)
DECLARE @TableName           VARCHAR(200)

SELECT @TableSQL = 'SELECT @columnsForInsertOUT = COALESCE(@columnsForInsertOUT' 
               + ''], ['', '''') 
               + name 
FROM MIGRATION_DICTIONARIES.dbo.' + @TableName + '_COLUMNS '

SET @ParmDefinition = '@columnsForInsertOUT varchar(400) OUTPUT'

EXECUTE sp_executesql
@TableSQL,
@ParmDefinition,
@columnsForInsertOUT=@columnsForInsert OUTPUT

SELECT @columnsForInsert
于 2013-05-09T10:28:11.347 回答