Reputation: 1044
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.
Upvotes: 0
Views: 883
Reputation: 6544
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
Upvotes: 1