Can we pass database name in a SQL query as parameter?

10,603

You can accomplish this using sp_executesql

DECLARE @Database   NVARCHAR(255),
        @Query      NVARCHAR(MAX)

SET @Database = 'Database'
SET @Query = N'SELECT * FROM ' + @Database + '.dbo.Table'

EXEC sp_executesql @Query
Share:
10,603
Tilak
Author by

Tilak

profile for Tilak on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/327255.png .NET Software programmer with interest in WPF, Linq, Debugging, Multithreading, and Design Patterns. Profile

Updated on June 28, 2022

Comments

  • Tilak
    Tilak almost 2 years

    Consider the following queries, where only database name differs (on same server)

    Select * from sampledev.dbo.Sample
    Select * from sampleqa.dbo.Sample
    

    The above queries are part of a procedure. Every time I have to run the procedure, I have to make sure it references the correct database (and do rename, if it is not).

    I want to pass the database name as a parameter to the stored procedure. The question is, is it possible? If yes, how?