如何使用SQL Server在变量中创建带有Select查询的Insert

时间:2016-02-11 07:12:33

标签: sql sql-server

如何使用SQL Server在变量中创建带有select查询的插入?

例如:

DECLARE @sqlCommand nvarchar(MAX)
DECLARE @odbname varchar(30)
DECLARE @m VARCHAR(20)
DECLARE @id VARCHAR(20)
DECLARE @br VARCHAR(30)
DECLARE @ndbname VARCHAR(30)

SET @ndbname='databasename'
SET @id = 2

SET @odbname = 'olddatabasename'
SET @br = 2

SET @m = 9

DECLARE @insert VARCHAR(MAX)
SET @insert = 'INSERT INTO'+ @ndbname+'.[pm]([pmId],[pmCode],[pmName])'  

EXEC (@insert)

SET @sqlCommand = 'SELECT @id AS spID,[spCode],[spName] `enter code here`FROM' + @0dbname+'.[sp] where spbID = @br and spID = @m'

EXECUTE sp_executesql @sqlCommand, N'@br nvarchar(75),@m nvarchar(75),@id VARCHAR(20)',@br = @br,@m=@m,@id=@id

实际上我需要在插入查询中执行的选择查询,即插入到另一个数据库表中的选定数据

2 个答案:

答案 0 :(得分:1)

SET @insert='INSERT INTO'+ @ndbname+'.[pm]([pmId],[pmCode],[pmName])'  
SET @sqlCommand = @insert + ' ' +'SELECT @id AS spID,[spCode],[spName] `enter code here`FROM' + @0dbname+'.[sp] where spbID = @br and spID = @m'
EXECUTE sp_executesql @sqlCommand, N'@br nvarchar(75),@m nvarchar(75),@id VARCHAR(20)',@br = @br,@m=@m,@id=@id

答案 1 :(得分:1)

有很多缺陷:

  • 您尝试单独执行INSERT
  • 如果您声明了dbName,则必须指定架构(是“dbo”?)
  • 你放出空间

如果您更改为此

SET @insert='INSERT INTO'+ @ndbname+'.[pm]([pmId],[pmCode],[pmName])'  
SET @sqlCommand = @insert + ' SELECT @id AS spID,[spCode],[spName] `enter code here`FROM' + @odbname+'.[sp] where spbID = @br and spID = @m'
PRINT @sqlCommand

你会得到这个:

INSERT INTOdatabasename.[pm]([pmId],[pmCode],[pmName]) SELECT @id AS spID,[spCode],[spName] `enter code here`FROMolddatabasename.[sp] where spbID = @br and spID = @m

但它应该是这样的

INSERT INTO databasename.[schema].[pm]([pmId],[pmCode],[pmName]) 
SELECT @id,[spCode],[spName] 
FROM olddatabasename.[schema].[sp] 
where spbID = @br and spID = @m

一般提示:

  • 如果您不需要,请不要使用动态SQL
  • 如果构建动态sql,请不要尝试执行它。而是打印它,将其复制到查询窗口并分析它是否正常