Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How to specify second DB in SSMS
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01683400
Message ID:
01683414
Views:
41
When I use dynamic sql and have WHERE clause I prefer to use sp_executesql SP. That way you avoid SQL Injections:
declare @cSecondDb as Varchar(100)
DECLARE @sql nvarchar(200)
declare @Category as Varchar(25);
set @Category = '1009F'
set @cSecondDb = 'SecondSQLDatabase'
SET @sql = 'select * from '+@cSecondDb+'..mytable where Category = @Category'
EXEC sp_executesql @sql, N'@Category varchar(25)', @Category = @Category
>Hi,
>
>I am testing the SQL Select with a name of the database not current.
>This case works:
>
>use [FirstSQLDatabase]
>go
>select * from SecondSQLDatabase..mytable where 1=1
>
>
>Now I want to put the 'SecondSQLDatabase' into a variable. Here is how I do it:
>
>use [FirstSQLDatabase]
>go 
>declare @cSecondDb as Varchar(100)
>set @cSecondDb = 'SecondSQLDatabase'
>select * from @cSecondDb..mytable where 1=1    -- this is the line that causes the syntax error.
>
>
>The above produces syntax error.
>
>What am I missing?
>TIA
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform