SQLCMD模式和CREATE VIEW中的变量

时间:2016-09-29 15:04:29

标签: sql sql-server-2008 sqlcmd

我试图在创建视图中使用sqlcmd模式变量 - 这是不可能的?

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

1 个答案:

答案 0 :(得分: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数据库项目为您处理此问题。