Assign a database name into the variable via SQL in SQL server
12,807
You can try the following query
DECLARE @DBname VARCHAR(MAX)
DECLARE @SQL VARCHAR(MAX)
SET @DBname = 'PatientTurningSystem'
SET @SQL = 'SELECT TABLE_NAME, TABLE_TYPE
FROM ' +@DBname+'.INFORMATION_SCHEMA.TABLES'
EXEC (@SQL)
Author by
Admin
Updated on June 07, 2022Comments
-
Admin almost 2 years
I want to assign database name into the declared variable and this is how I tried already:
DECLARE @DBname VARCHAR(100) SET @DBname = 'PatientTurningSystem' SELECT TABLE_NAME, TABLE_TYPE FROM @DBname.INFORMATION_SCHEMA.TABLES
But I get the following error:Msg 102, Level 15, State 1, Procedure SP_TableDeatails, Line 8
Incorrect syntax near '.' -
Admin almost 6 yearsit doesn't work for me. this error is: Msg 911, Level 16, State 4, Line 14 Database 'SELECT TABLE_NAME, TABLE_TYPE FROM PatientTurningSystem' does not exist. Make sure that the name is entered correctly.
-
marc_s almost 6 yearsFirst off, the
@DBName
really must have a length in its declaration - otherwise, this is never going to work. And secondly, theEXEC
function expects anNVARCHAR
- so please define your@Query
to beNVARCHAR
, and use theN'....'
prefix when settings its value -
Alfin E. R. almost 6 years@marc_s since Query should be NVARCHAR, should the Dbname also need to be NVARCHAR as well?
-
Gopakumar N.Kurup almost 6 yearsJust EXEC(@QUERY) will work. Also please declare the @DBName as VARCHAR(255)