views:

19

answers:

1

I need to update a table from another table several times in succession. In order to make this script easier for people to use, I'd like to be able to dynamically reference it. Something like this:

declare @databasename sysname
set @databasename = 'm2mdata01.dbo'

select * from @databasename.mytable

This isn't working. Any suggestions as to how I can accomplish this?

+1  A: 

You can't use variables in the FROM clause in a SQL statement. You would have to use dynamic SQL, such as this:

declare @databasename sysname
set @databasename = 'm2mdata01.dbo'
EXEC ('select * from ' + @databasename + '.mytable')
bobs
Any other options? If I have to edit the code to do that it'll be a huge mess.
DavidStein
if database is the only dynamic component of the SQL script, you can take advantage of the `USE database` command. However, you can't use variables with it either. But, you might find a way to set the database before running the statement.
bobs