SQLCMD模式和CREATE VIEW内部的变量
问题描述:
我正在尝试在创建视图中使用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
答
是的,这是可能的。无论如何,你似乎并没有设置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数据库项目为您处理此问题。
为什么不使用实际的db名称而不是变量? –
变量可能有用。例如,在生产中,您可能希望将数据库B移动到不同的服务器,并使视图/过程在原始服务器上的数据库A中使用它。同时,在开发中,它们都在同一台服务器上。如果您将数据库名称硬编码到开发中,那么它会使生产中的数据库A更新变得非常困难。 –