Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How to specify second DB in SSMS
Message
From
31/01/2022 16:29:15
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01683400
Message ID:
01683407
Views:
37
Were you using something like the following?
use [FirstSQLDatabase];
go 
declare @cSecondDb as Varchar(100);
declare @sql as varchar(max);
declare @Category as Varchar(25);
set @Category = '1009F';
set @cSecondDb = 'SecondSQLDatabase';
set @sql = 'select * from ' + @cSecondDb + '.dbo.mytable' + ' WHERE  Category = ' + @Category
exec (@sql);
>I know that I am missing something simple. But how do I add a WHERE clause to the dynamic SQL?
>For example, say I want to add to the SQL Select below:
>
>declare @Category as Varchar(25);
>set @Category = '1009F';
>' WHERE  Category = @Category'
>
>I get error no matter what I do with the @Category.
>
>>Hi Dmitry,
>>
>>Use dynamic SQL, something like this:
>>
>>use [FirstSQLDatabase];
>>go 
>>declare @cSecondDb as Varchar(100);
>>declare @sql as varchar(max);
>>set @cSecondDb = 'SecondSQLDatabase';
>>set @sql = 'select * from ' + @cSecondDb + '.dbo.mytable';
>>exec (@sql);
>>
>>
>>and replace dbo with the appropriate schema name if it's not dbo.
>>
>>
>>>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
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform