Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 from database as a variable

Author  Topic 

matt1988
Starting Member

1 Post

Posted - 2009-06-29 : 12:46:18
Hello,

I am trying to write a script that has to use multiple databases. For this, I need to be able to store the database that I am trying to pull from as a variable that I can use in all of the statements later.

I have tried something like this:

DECLARE @destTable nvarchar(256)
set @destDB = 'matt_scratch.dbo'
Declare @ID int
set @ID = select UID from @destDB.Table


With no luck. I see that I can do something like make a query string out of the nvarchar and then execute that, but that runs me into some other problems.

Sorry if I didn't explain that well, let me know if you have any questions.

Thank you in advance,

Matt

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-06-29 : 13:06:40
You will need to use dynamic SQL for this.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-29 : 13:49:37
can i ask the need to append db name in script? isn't it enough to put the script in a execute sql task in ssis package inside a for each loop which loops through your databases and executes it on each db?
Go to Top of Page
   

- Advertisement -