动态SQL插入语句

时间:2013-12-28 12:58:38

标签: sql sql-server sql-server-2008 insert

我在下面的声明中没有效果。有什么想法吗?

DECLARE @TargetDB NVARCHAR(50)
DECLARE @SourceDB NVARCHAR(50)
DECLARE @InsetRecords NVARCHAR(1000)
SET @TargetDB = 'MySSISDb'
SET @SourceDB = 'MySSISDb'

SET @InsetRecords = 'INSERT INTO  + @TargetDB + .dbo.Item2(ProductNumber, ProductName) SELECT(ProductNumber, ProductName) FROM  + @SourceDB + .dbo.Item'
EXEC (@InsetRecords)

1 个答案:

答案 0 :(得分:0)

问题似乎是您的动态SQL不是真正的动态SQL。您没有插入变量的值,而是将变量名称添加到SQL字符串。

尝试替换该行:

SET @InsetRecords = 'INSERT INTO  + @TargetDB + .dbo.Item2(ProductNumber, 
ProductName) SELECT(ProductNumber, ProductName) FROM  + @SourceDB + .dbo.Item'

使用:

SET @InsetRecords = 'INSERT INTO ' + @TargetDB + '.dbo.Item2(ProductNumber, 
ProductName) SELECT(ProductNumber, ProductName) FROM ' + @SourceDB + '.dbo.Item'