1

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?

1

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.