Variable to select database in SQL query
2
votes
1
answer
5166
views
If I want use a variable in the
FROM
clause of a SQL query I [need to use dynamic SQL.](https://stackoverflow.com/a/41250925/2112418) Which might be a pain if the query is long and complex.
There are few different ways of running a query from a database you are not currently connected to. The two methods I use most often are these..
Select * from msdb..sysjobs_view
or
USE MSDB
Select * from sysjobs_view
If you start on the master database both of the above will give you the same results.
When I put these both into dynamic SQL one works and the other does not
Starting from master, this works
DECLARE @DBN SYSNAME
SET @DBN = 'msdb'
DECLARE @Sql NVARCHAR(MAX)
SET @Sql = N'Select * from ' + @DBN + '..sysjobs_view'
EXEC (@Sql)
But this does not
DECLARE @DBN SYSNAME
SET @DBN = 'msdb'
DECLARE @Sql NVARCHAR(MAX)
SET @Sql = N'USE ' + @DBN
EXEC (@Sql)
Select * from sysjobs_view
I get the error
> Msg 156, Level 15, State 1, Line 14
> Incorrect syntax near the keyword 'EXEC'.
My reason for this: One line of dynamic SQL in big complex query is going to be less painful to code than trying to turn the whole query into dynamic SQL. My question here is just about why its not working with the USE
clause.
Why can't I use dynamic SQL with the [USE
clause](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/use-transact-sql?view=sql-server-ver15) to change the database context?
NOTE: The below does work and would be easy to code. But my question about why remains.
DECLARE @DBN SYSNAME
SET @DBN = 'msdb'
DECLARE @Sql NVARCHAR(MAX)
SET @Sql = N'USE ' + @DBN +'
Select * from sysjobs_view
'
EXEC (@Sql)
Asked by James Jenkins
(6318 rep)
Nov 13, 2019, 04:59 PM
Last activity: Dec 17, 2019, 06:23 PM
Last activity: Dec 17, 2019, 06:23 PM