How to pass Database name as a parameter in SQL Server

Bandi
Posted by Bandi under Sql Server category on | Points: 40 | Views : 952
--Passing Database Name as a parameter
DECLARE @DBNAME VARCHAR(50), @DynSQL VARCHAR(MAX) = ''
SET @DBNAME = 'study'
-- Fetch any table data from a database, here database name is passed via variable
SELECT * FROM @DBNAME.dbo.Employees


It results Syntax error as below,
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '.'.


To pass database name or any object name as parameter value, we have to use dynamic SQL

DECLARE @DBNAME VARCHAR(50), @DynSQL VARCHAR(MAX) = ''
SET @DBNAME = 'study'
SET @DynSQL = ' SELECT * FROM ' + @DBNAME + '..employees; '
EXEC (@DynSQL)

Comments or Responses

Login to post response