0

I have written a T-SQL script that migrates some data from one database to another. At the moment I am doing that by use of dynamic sql.

For example see the following code:

Declare @sqlquery nvarchar(4000)
SET @sqlquery = N'SELECT * from ' + @LinkServerName + @SourceDatabaseName + '.dbo.Table'
EXEC @sqlquery

In this example @LinkServerName is a nvarchar variable that stores the name of the linked server for the SQL Server that contains the source database. @SourceDatabaseName is a nvarchar variable that stores the name of the source database.

I don´t like that way. I would prefer the following code:

SELECT * from @SourceDatabase.dbo.Table

Is that possible?

Thank you in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Andre
  • 1,044
  • 1
  • 11
  • 23
  • No, that second approach **is not valid T-SQL** since you cannot use variables for column or table names in your T-SQL statement. – marc_s Aug 02 '12 at 10:00
  • possible duplicate of [How to use variable for database name in t-sql](http://stackoverflow.com/questions/727788/how-to-use-variable-for-database-name-in-t-sql) – Pondlife Aug 02 '12 at 21:29

1 Answers1

1

Second approach is incorrect, first one is the correct one. For more information check this other question here at stackoverflow how-to-use-variable-for-database-name-in-t-sql

Community
  • 1
  • 1
Yaroslav
  • 6,476
  • 10
  • 48
  • 89