Dynamic Database Name and Schema/Owner assignment
I need to update a table from another table several times in succession. In order to make this script easier for开发者_如何学Python 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?
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')
精彩评论