I need to execute certain script on various SQL Server instances. They use the database with a different identification. However, all the databases have the same table (same name and structure) that should be processed. Because of that I want to detect the name of the database, set it to a string variable, construct the SQL statement, and execute the constructed string via sp_executesql. The bare command that executes correctly is:
USE [1000574];
SELECT TOP 10 temperature_1, UTC FROM dbo.Data;
Then I am trying to execute the equivalent string with the @database_name placeholder:
DECLARE @database_name nvarchar(100);
SET @database_name = '1000574';
EXEC sp_executesql N'USE [@database_name];
SELECT TOP 10 temperature_1, UTC FROM dbo.Data;',
N'@database_name nvarchar(100)',
@database_name = @database_name
What I get is the following error message:
*Msg 911, Level 16, State 1, Line 1
Database ‘@database_name’ does not exist. Make sure that the name is entered correctly.*
Where is the error?
Thanks, Petr
You cannot parameterize the argument to
use: it expects a literal. Construct the query dynamically instead: