2010-09-28 4 views

risposta

5

Per fare ciò è necessario utilizzare SP_ExecuteSQL. cioè query dinamica esecuzione

Esempio:

EXECUTE sp_executesql 
      N'SELECT * FROM AdventureWorks2008R2.HumanResources.Employee 
      WHERE BusinessEntityID = @level', 
      N'@level tinyint', 
      @level = 109; 
+0

non ha funzionato per questo: ESEGUI sp_executesql N'update @ sourceDatabase.dbo.PredictedPrices set MINPRICE = MINPRICE' – Michel

+0

stesso errore: sintassi errata vicino a "." – Michel

+0

@Michel - È necessario concatenare la stringa. Vedi la mia risposta per un esempio. –

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; 
+2

+1, bel esempio completo e uso di QUOTENAME() –

4

Se si esegue questo script in SSMS, è possibile utilizzare SQLCMD Mode (che si trova sotto il menu Query) per lo script una variabile per il database nome:

:setvar sourceDatabase YourDatabaseName 

update $(sourceDatabase).dbo.PredictedPrices 
    set ... 
+0

Nice ........... – Michel