创建索引视图时出现问题

时间:2018-02-20 16:48:44

标签: sql sql-server tsql

我需要使用UNION ALL从同一数据库的50个不同表创建索引视图。 我尝试使用以下查询抛出错误,

USE ABC
GO
CREATE VIEW QID_Consolidated_View([ID],[METRIC],[PT_FIRST_NM],[PT_LAST_NM],[D1],[D2],[D3],[RE1],[RE2],[N1],[N2],[N3],[PE1],[RD],[RN],[PD],[PN],[RD_Calc],[RN_Calc],[PD_Calc],[PN_Calc],[Comments])

WITH SCHEMABINDING

AS
    SELECT ROW_NUMBER() OVER( ORDER BY METRIC ) AS ID,[METRIC],[PT_FIRST_NM],[PT_LAST_NM],[D1],[D2],[D3],[RE1],[N1],[N2],[N3],[PE1],[RD],[RN],[PD],[PN],[RD_Calc],[RN_Calc],[PD_Calc],[PN_Calc],[Comments] from
         (
        -------------------------------001-------------------------------
         SELECT 'QID 001' as METRIC,[PT_FIRST_NM],[PT_LAST_NM],cast([D1] as int) as D1,cast([D2] as char(4)) as D2,cast([D3] as int) as D3,cast([RE1] as int) as [RE1]
              ,cast([N1] as int) as N1,cast([N2] as int) as [N2],cast([N3] as int) as N3,cast([PE1] as int) as [PE1]
              ,cast([RD] as int) as [RD],cast([RN] as int) as [RN],cast([PD] as int) as [PD],cast([PN] as int) as [PN],cast([RD_Calc] as int) as [RD_Calc]
              ,cast([RN_Calc] as int) as [RN_Calc] ,cast([PD_Calc] as int) as [PD_Calc],cast([PN_Calc] as int) as [PN_Calc],[Comments]
        FROM dbo.[001]
        UNION ALL
        -------------------------------002-------------------------------
        SELECT 'QID 012' as METRIC,[PT_FIRST_NM],[PT_LAST_NM],cast([D1] as int) as D1,cast([D2] as char(4)) as D2,cast([D3] as int) as D3,cast([RE1] as int) as [RE1]
              ,cast([N1] as int) as N1,cast([N2] as int) as [N2],cast([N3] as int) as N3,cast([PE1] as int) as [PE1]
              ,cast([RD] as int) as [RD],cast([RN] as int) as [RN],cast([PD] as int) as [PD],cast([PN] as int) as [PN],cast([RD_Calc] as int) as [RD_Calc]
              ,cast([RN_Calc] as int) as [RN_Calc] ,cast([PD_Calc] as int) as [PD_Calc],cast([PN_Calc] as int) as [PN_Calc],[Comments]
        FROM dbo.[002]
        UNION ALL
        -------------------------------003-------------------------------
        SELECT 'QID 014' as METRIC,[PT_FIRST_NM],[PT_LAST_NM],cast([D1] as int) as D1,cast([D2] as char(4)) as D2,cast([D3] as int) as D3,cast([RE1] as int) as [RE1]
              ,cast([N1] as int) as N1,cast([N2] as int) as [N2],cast([N3] as int) as N3,cast([PE1] as int) as [PE1]
              ,cast([RD] as int) as [RD],cast([RN] as int) as [RN],cast([PD] as int) as [PD],cast([PN] as int) as [PN],cast([RD_Calc] as int) as [RD_Calc]
              ,cast([RN_Calc] as int) as [RN_Calc] ,cast([PD_Calc] as int) as [PD_Calc],cast([PN_Calc] as int) as [PN_Calc],[Comments]
        FROM dbo.[003]

        )
    A

    GO

    CREATE UNIQUE CLUSTERED INDEX
        IDX_QID_Consolidated_View_ID ON dbo.QID_Consolidated_View(ID)

错误是:

  

无法在视图“ABC.dbo.QID_Consolidated_View”上创建索引,因为它   引用派生表“A”(由FROM中的SELECT语句定义)   条款)。考虑删除对派生表的引用   索引视图。

有人可以帮我解决这个问题吗? 提前谢谢!

1 个答案:

答案 0 :(得分:2)

查看"附加要求"此BOL link中的部分列出了您可以和可以使用索引视图执行的操作。不允许派生表

enter image description here