是否可以做这样的事情:
DECLARE @SourceDB VARCHAR(100);
SET @SourceDB = [DatabaseName]
INSERT INTO CompletedScope
( uidInstanceID ,
completedScopeID ,
state ,
modified
)
SELECT uidInstanceID ,
completedScopeID ,
state ,
modified
FROM SourceDB.[dbo].CompletedScope;
基本上在查询中使用声明的SourceDB变量。
答案 0 :(得分:4)
您需要使用Dynamic sql ...
DECLARE @SourceDB NVARCHAR(128), @Sql NVARCHAR(MAX);
SET @SourceDB = 'DatabaseName';
SET @Sql = N'INSERT INTO CompletedScope
( uidInstanceID ,
completedScopeID ,
state ,
modified
)
SELECT uidInstanceID ,
completedScopeID ,
state ,
modified
FROM ' + QUOTENAME(@SourceDB) + '.[dbo].CompletedScope;'
EXECUTE sp_executesql @Sql
在将变量连接到sql时使用QUOTENAME()
函数,保护您免受Sql Injection攻击。
答案 1 :(得分:3)
您可以使用动态查询
SELECT @sql=
'INSERT INTO CompletedScope
( uidInstanceID ,
completedScopeID ,
state ,
modified
)
SELECT uidInstanceID ,
completedScopeID ,
state ,
modified
FROM ' + @SourceDB + '.[dbo].CompletedScope;'
EXEC sp_executesql @sql