2016-09-29 25 views
0

我正在嘗試在創建視圖中使用sqlcmd模式變量 - 這不可能嗎?SQLCMD模式和CREATE VIEW內部的變量

IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[newTaxonomyMatterTypeId]')) 
Drop view newTaxonomyMatterTypeId; 
go 
-- Create a view that has all of practice areas and all of Matters within the practice area using the new Taxonomy table 
Create View NewTaxonomyMatterTypeId as (
select p.PracticeAreaId As NewPracticeAreaId, p.PracticeAreaEn, mt.MatterTypeId As NewMatterTypeId, mt.MatterTypeEn 
    from [$(Taxonomy_DB)].dbo.PracticeAreas p 
    inner join [$(Taxonomy_DB)].dbo.MatterTypes mt on p.PracticeAreaId = mt.PracticeAreaID 
    ) 
Go 

請指教。

感謝, KS

+0

爲什麼不使用實際的db名稱而不是變量? –

+0

變量可能有用。例如,在生產中,您可能希望將數據庫B移動到不同的服務器,並使視圖/過程在原始服務器上的數據庫A中使用它。同時,在開發中,它們都在同一臺服務器上。如果您將數據庫名稱硬編碼到開發中,那麼它會使生產中的數據庫A更新變得非常困難。 –

回答

0

是的,這是可能的。無論如何,你似乎並沒有設置Taxonomy_DB變量。首先,確保你的SSMS在SQLCMD模式(查詢> SQLCMD模式),然後設置使用setvar

:setvar Taxonomy_DB yourDbName 
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[newTaxonomyMatterTypeId]')) 
Drop view newTaxonomyMatterTypeId; 
go 
-- Create a view that has all of practice areas and all of Matters within the practice area using the new Taxonomy table 
Create View NewTaxonomyMatterTypeId as (
select p.PracticeAreaId As NewPracticeAreaId, p.PracticeAreaEn, mt.MatterTypeId As NewMatterTypeId, mt.MatterTypeEn 
    from [$(Taxonomy_DB)].dbo.PracticeAreas p 
    inner join [$(Taxonomy_DB)].dbo.MatterTypes mt on p.PracticeAreaId = mt.PracticeAreaID 
    ) 
Go 

或者你的變量,無論是在同一個腳本或調用腳本,例如:

:setvar Taxonomy_DB yourDbName 
:r "c:\temp\yourview.sql" 

您還可以在使用sqlcmd.exe-v開關時設置sqlcmd變量,或讓Visual Studio數據庫項目爲您處理此問題。