如何使用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
实际上我需要在插入查询中执行的选择查询,即插入到另一个数据库表中的选定数据
答案 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)
有很多缺陷:
如果您更改为此
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
一般提示: