更改现有VIEW的SCHEMABINDING

时间:2018-06-11 14:38:10

标签: sql-server tsql sql-server-data-tools

我有一个现有的数据库(SSDT项目作为源代码),我必须在其中更新表格。我只是将列类型从nvarchar(MAX)更改为nvachar(256)。问题是,我有一个与SCHEMABINDING绑定到此表的现有视图。我无法编辑表格列,因为SCHEMABINDING会阻止影响VIEW的更改。

以下脚本在PreDeploymentScript中执行。当我调用DROP VIEW [base].[VIEW_DEPENDING_ON_TABLE]语句时,部署后缺少视图。我的想法是,在部署期间禁用SCHEMABINDING并在完成后启用它。在TSQL脚本中这怎么可能?或者有更好的方法吗?

IF EXISTS ( SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = N'base'
        AND TABLE_NAME = 'TABLENAME'
        AND COLUMN_NAME = 'Instance'
        AND CHARACTER_MAXIMUM_LENGTH = -1)
AND NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IX_TABLENAME_Instance' AND object_id = OBJECT_ID(N'[base].[TABLENAME]'))
BEGIN

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[base].[VIEW_DEPENDING_ON_TABLE]') AND type in (N'V'))
    BEGIN
        DROP VIEW [base].[VIEW_DEPENDING_ON_TABLE]
    END

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[base].[TABLENAME]') AND type in (N'U'))
    BEGIN
        UPDATE [base].[TABLENAME] SET [Instance] = LEFT(Instance, 256)
        ALTER TABLE [base].[TABLENAME] ALTER COLUMN [Instance] NVARCHAR(256)
    END

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[base].[TABLENAME]') AND type in (N'U'))
    BEGIN
        CREATE NONCLUSTERED INDEX [IX_TABLENAME_Instance] ON [base].[TABLENAME]
        (
            [Instance] ASC
        ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    END
END
GO

1 个答案:

答案 0 :(得分:2)

没有命令禁用WITH SCHEMABINDING。您可以通过删除视图并在没有选项的情况下重新创建视图,或者只是更改它来执行此操作。在你的情况下:

ALTER VIEW [base].[VIEW_DEPENDING_ON_TABLE]
-- WITH SCHEMABINDING
AS
    SELECT ...;

对基础表进行更改后,可以再次更改视图:

ALTER VIEW [base].[VIEW_DEPENDING_ON_TABLE]
WITH SCHEMABINDING
AS
    SELECT ...;

没有方便的脚本?没关系,您可以从sys.sql_modules提取,但需要进行一些按摩才能从CREATE转换为ALTER并删除WITH SCHEMABINDING。您可以编写解析它的代码,但这非常脆弱,因为替换或评论短语“with schemabinding”可能非常困难 - 它可能有多个空格,制表符,回车符,非打印字符等,它也可能存在于代码的其他部分(如注释,甚至是表或列别名)。