Link to home
Start Free TrialLog in
Avatar of Shanmugam Rajagopal
Shanmugam Rajagopal

asked on

How to use DB name as variable in a Query in Sql Server Stored Procedure

I am using 2 databases in SQL Server. Based on 1 query get Master DB name from a DB table. Using that Master DB table get values . Following is the SQL I used. I stored variable of DB name and I am not sure how to use it in 2nd query. Please help.


declare @dbname varchar(20);
declare @sql varchar(1000);
select @dbname = Databasename from ParentTable Where DBaseID = 1
      go
      set @sql = "Select B.Id, B.Name from tbl A JOIN @dbname..tbl1 B on A.CID = B.CID"
      go
      execute sp_executesql @sql
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

you can try this:
set @sql = "Select B.Id, B.Name from tbl A JOIN " + @dbname + "..tbl1 B on A.CID = B.CID"

Open in new window

Avatar of Shanmugam Rajagopal
Shanmugam Rajagopal

ASKER

It didn't work
what do you see if you do
select @sql

Open in new window

Get rid of the GOs:
declare @dbname varchar(20);
declare @sql varchar(1000);
select @dbname = Databasename from ParentTable Where DBaseID = 1
set @sql = "Select B.Id, B.Name from tbl A JOIN " + @dbname + "..tbl1 B on A.CID = B.CID"
execute sp_executesql @sql 

Open in new window

Vitor is right, the GO statements can't be there!
ASKER CERTIFIED SOLUTION
Avatar of Shanmugam Rajagopal
Shanmugam Rajagopal

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for your help folks
If you put back the GO it won't work, right?
I added Go just for sample. The original problem is using variable of another select statement in 2nd sql. That is the subject of this issue too.

Thanks for following up
vidhyashan, don't forget to mark one or more comments as solution to have this question closed.
Cheers
Recommendation to close this question by accepting the above comment as solution.