T-SQL: can I use a variable as a database reference
Asked Answered
S

3

6

I want to accomplish this:

update @sourceDatabase.dbo.PredictedPrices

and then set @sourceDatabase as a variable.

But I'm not allowed?

Incorrect syntax near '.'.

Is there another way?

Sheepfold answered 28/9, 2010 at 9:5 Comment(0)
U
5

For this to be done you need to use SP_ExecuteSQL . i.e dynamic query execution

Example:

EXECUTE sp_executesql 
          N'SELECT * FROM AdventureWorks2008R2.HumanResources.Employee 
          WHERE BusinessEntityID = @level',
          N'@level tinyint',
          @level = 109;
Ulema answered 28/9, 2010 at 9:8 Comment(2)
didn't work for this: EXECUTE sp_executesql N'update @sourceDatabase.dbo.PredictedPrices set MinPrice = MinPrice'Sheepfold
@Sheepfold - You need to concatenate into the string. See my answer for an example.Buzzard
B
8
DECLARE @Dynsql NVARCHAR(MAX)
DECLARE @sourceDatabase sysname
DECLARE @MinPrice MONEY

SET @sourceDatabase = 'foo'
SET @MinPrice = 1.00

SET @Dynsql =  N'update ' + QUOTENAME(@sourceDatabase) + '.dbo.PredictedPrices 
       set MinPrice = @MinPrice'


EXECUTE sp_executesql   @Dynsql,
                      N'@MinPrice money',
                        @MinPrice = @MinPrice;
Buzzard answered 28/9, 2010 at 9:34 Comment(0)
U
5

For this to be done you need to use SP_ExecuteSQL . i.e dynamic query execution

Example:

EXECUTE sp_executesql 
          N'SELECT * FROM AdventureWorks2008R2.HumanResources.Employee 
          WHERE BusinessEntityID = @level',
          N'@level tinyint',
          @level = 109;
Ulema answered 28/9, 2010 at 9:8 Comment(2)
didn't work for this: EXECUTE sp_executesql N'update @sourceDatabase.dbo.PredictedPrices set MinPrice = MinPrice'Sheepfold
@Sheepfold - You need to concatenate into the string. See my answer for an example.Buzzard
F
4

If you're running this script in SSMS, you can use SQLCMD Mode (found under the Query menu) to script a variable for your database name:

:setvar sourceDatabase YourDatabaseName

update $(sourceDatabase).dbo.PredictedPrices
    set ...
Foreworn answered 28/9, 2010 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.