【问题标题】:SQLCMD mode and variables inside CREATE VIEWSQLCMD 模式和 CREATE VIEW 中的变量
【发布时间】:2016-09-29 15:04:29
【问题描述】:

我正在尝试在我的创建视图中使用 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

【问题讨论】:

  • 为什么不使用实际的数据库名称而不是变量?
  • 变量可能很有用。例如,在生产中,您可能希望将数据库 B 移动到不同的服务器,并让视图/过程从原始服务器上的数据库 A 中使用它。同时,在开发中,它们都在同一台服务器上。如果您将数据库名称硬编码到其中以进行开发,那么在生产环境中更新数据库 A 会非常困难。

标签: sql sql-server-2008 sqlcmd


【解决方案1】:

是的,这是可能的。无论如何,您似乎都没有设置 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 数据库项目为您处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-10
    • 2016-05-11
    • 2013-05-15
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多