I am trying to pass a database name in as a parameter and execute some dynamic SQL. As a test I created this:
declare @HRMSDatabase_1 nvarchar(50) = N'FirstDatabase',
@Example_1 nvarchar(max) =
'select @HRMSDatabase'
execute sp_executesql @Example_1, N'@HRMSDatabase nvarchar(50)', @HRMSDatabase_1
which returns FirstDatabase as I expected.
When I try this:
declare @HRMSDatabase_2 nvarchar(50) = N'FirstDatabase',
@Example_2 nvarchar(max) =
'select
''Test''
from
@HRMSDatabase.dbo.hrpersnl hp'
execute sp_executesql @Example_2, N'@HRMSDatabase nvarchar(50)', @HRMSDatabase_2
I get an error message:
Msg 102, Level 15, State 1, Line 29
Incorrect syntax near '.'.
Is what I am trying to do possible? I cannot simply use a USE FirstDatabase as I have a few databases I have to query in the same dynamic SQL using inner joins.
Also, I cannot use SQLCMD as this script gets executed from a GUI.
Also, I cannot use SQLCMD as this script gets executed from a GUI.- that doesnt explicitly stop you using SQLCMD! Its wrapped up as a callable utility: learn.microsoft.com/en-us/sql/tools/sqlcmd-utilityfrom @HRMSDatabase.dbo.hrpersnl hp'need to befrom '+ @HRMSDatabas+'.dbo.hrpersnl hp'for the variable to be evaluated in the dynamic SQL?Sales2015andSales2016databases, there should be aSalesdatabase and then the year (or date) information should be present in appropriate column(s) in the relevant table(s))