Reputation: 21226
This statement works:
INSERT INTO TestDB2.dbo.MyTableName SELECT * FROM TestDB1.dbo2.MyTableName
This statement works not:
DECLARE @SourceDatabase varchar(50)
DECLARE @TargetDatabase varchar(50)
SET @SourceDatabase = 'TestDB1'
SET @TargetDatabase = 'TestDB2'
INSERT INTO @TargetDatabase.dbo.PrcConfiguration SELECT * FROM @SourceDatabase.sppm.CONFIGURATION
OR without the '@'
INSERT INTO TargetDatabase.dbo.PrcConfiguration SELECT * FROM SourceDatabase.dbo1.CONFIGURATION
dbo and dbo1 are the schema.
I want to move later data from multiple tables from one database to another database using the same tables.
What do I wrong?
Upvotes: 1
Views: 105
Reputation: 21776
You cannot pass the DB name in such a query in variable, use dynamic querying instead:
DECLARE @SourceDatabase varchar(50)
DECLARE @TargetDatabase varchar(50)
DECLARE @sql NVARCHAR(MAX)
SET @SourceDatabase = 'TestDB1'
SET @TargetDatabase = 'TestDB2'
SET @sql = N'INSERT INTO ['+@TargetDatabase+N'].dbo.PrcConfiguration SELECT * FROM ['+@SourceDatabase+N'].sppm.CONFIGURATION'
exec(@sql)
Upvotes: 1