Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 871
Michel Avatar asked Sep 28 '10 09:09

Michel


1 Answers

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;
like image 127
Martin Smith Avatar answered Sep 22 '22 02:09

Martin Smith