【发布时间】:2022-01-14 15:20:46
【问题描述】:
感谢您帮助我解决在 3 个数据库(同一服务器)之间传输数据的问题。
我想修改问题
假设我有 3 个数据库:Data1 和 Data2 和 Data3。
并且在这些数据中存在相同的表和列。
现在我使用这个命令,它工作正常
CREATE PROCEDURE [dbo].[copy]
@id_id INT,
@namecreate Nvarchar(50),
@txtdataname sysname
AS BEGIN
DECLARE @InsertedRows TABLE (id INT)
--Insert Master
insert into [Data2].[dbo].[Table1] (cot1, cot2, cot3, cot4, namecreate)
OUTPUT inserted.id
INTO @InsertedRows
SELECT cot1, cot2, cot3, cot4, @namecreate From Table1 WHERE (id = @id_id)
--Insert Detail
insert into [Data2].[dbo].[Table2] (id, cot1, cot2, cot3, cot4)
SELECT (SELECT TOP (1) id FROM @InsertedRows), cot1, cot2, cot3, cot4 From Table2 WHERE (id = @id_id)
END
我想将那个 Data2 位置更改为 @txtdataname 中传递的动态 因为我尝试这样写,所以报错了
CREATE PROCEDURE [dbo].[copy]
@id_id INT,
@namecreate Nvarchar(50),
@txtdataname sysname
AS BEGIN
DECLARE @InsertedRows TABLE (id INT)
--Insert Master
insert into [@txtdataname].[dbo].[Table1] (cot1, cot2, cot3, cot4, namecreate)
OUTPUT inserted.id
INTO @InsertedRows
SELECT cot1, cot2, cot3, cot4, @namecreate From Table1 WHERE (id = @id_id)
--Insert Detail
insert into [@txtdataname].[dbo].[Table2] (id, cot1, cot2, cot3, cot4)
SELECT (SELECT TOP (1) id FROM @InsertedRows), cot1, cot2, cot3, cot4 From Table2 WHERE (id = @id_id)
END
【问题讨论】:
-
您不能用变量替换表名。您将需要使用动态 sql sp_executesql 来做到这一点
-
对了,标题说的是
from one server to another,其实你是transferring data between 3 Databases (same server) -
对象名称是 unicode 并且具有特定长度 - 使用 sysname。并且停止使用将“类型”添加到变量名的可怕做法。
标签: sql sql-server