Search code examples
sql-serverselectconcatenationdeclare

How to parameterize database name in SQL Server


I have the list of servers and databases, trying to use OLTP and WH database in the same script as below.

DECLARE @oltp VARCHAR(50)
SET @oltp = 'Employee'

DECLARE @wh VARCHAR(25)
SET @wh = @oltp + '_wh'
   
SELECT * 
FROM Employee_wh..employee_sales_item --working

SELECT * 
FROM @wh..employee_sales_item --not working

I'm getting the following exception

Msg 102, Level 15, State 1, Line 86
Incorrect syntax near '.'.

Please help me to fix @wh..employee_sales_item using the declared variable.


Solution

  • DECLARE @oltp VARCHAR(50)
    SET @oltp = 'Employee';
    
    DECLARE @wh VARCHAR(25)
    SET @wh =  '_wh';
    
    DECLARE @DatabaseName SYSNAME = @oltp + @wh;
       
    IF NOT EXISTS ( SELECT 1 FROM sys.databases WHERE name = @DatabaseName)
        BEGIN
          DECLARE @ErrorMsg VARCHAR(1000);
          SET @ErrorMsg = QUOTENAME(@DatabaseName)  + ' database does not exist';
          RAISERROR(@ErrorMsg , 16 , 2); 
        END
    ELSE 
    BEGIN
        DECLARE @Sql NVARCHAR(MAX) = N'SELECT * FROM '  
                                   + QUOTENAME(@DatabaseName) 
                                   + N'..employee_sales_item;';
    
        EXEC sys.sp_executesql @Sql;
    END