[英]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. 然后将@sourceDatabase
设置为变量。
But I'm not allowed? 但我不被允许?
Incorrect syntax near '.'.
Is there another way? 还有另外一种方法吗?
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;
For this to be done you need to use SP_ExecuteSQL
. 要完成此操作,您需要使用SP_ExecuteSQL
。 ie dynamic query execution 即动态查询执行
Example: 例:
EXECUTE sp_executesql
N'SELECT * FROM AdventureWorks2008R2.HumanResources.Employee
WHERE BusinessEntityID = @level',
N'@level tinyint',
@level = 109;
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: 如果您在SSMS中运行此脚本,则可以使用SQLCMD模式 (在“查询”菜单下找到)为您的数据库名称编写变量脚本:
:setvar sourceDatabase YourDatabaseName
update $(sourceDatabase).dbo.PredictedPrices
set ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.