创建索引视图

时间:2012-06-14 06:12:24

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我的表结构如下:

MyTable (ID Int, AccID1 Int, AccID2 Int, AccID3 int)

 ID      AccID1      AccID2      AccID3
----    --------    --------    --------
  1        12          2          NULL
  2        4           12           1
  3       NULL        NULL          5
  4        7          NULL          1   

我想用下面的输出创建索引视图:

 ID    Level     Value
----   -----    -------
 1       1         12
 1       2         2 
 2       1         4
 2       2         12
 2       3         1
 3       3         5
 4       1         7
 4       3         1

编辑:

我的桌子很大,我希望有上面的输出。 我可以获取如下的查询:

Select  ID,
        Case StrLevel
            When  'AccID1' Then 1
            When  'AccID2' Then 2
            Else 3
        End AS [Level],
        AccID as Value
From    (
        Select A.ID, A.AccID1, A.AccID2, A.AccID3
        From MyTable A
        )as p
UNPIVOT (AccID FOR [StrLevel] IN (AccID1, AccID2, AccID3)) AS unpvt

Select *
from (
        select MyTable.ID,
                num.n as [Level],
                Case Num.n
                    When 1 Then MyTable.AccID1
                    When 2 Then MyTable.AccID2
                    Else MyTable.AccID3
                End AS AccID
        from myTable
        cross join (select 1
                    union select 2
                    union select 3)Num(n)
    )Z
Where Z.AccID IS NOT NULL

    Select  A.ID,
            2 AS [Level],
            A.AccID1 AS AccID
     From MyTable A
     Where A.AccID1 IS NOT NULL

    Union

    Select  A.ID,
            2 AS [Level],
            A.AccID2
     From MyTable A
     Where A.AccID2 IS NOT NULL

    Union

    Select  A.ID,
            3 AS [Level],
            A.AccID3
     From MyTable A
     Where A.AccID3 IS NOT NULL  

但是上面的查询很慢,我希望索引视图有更好的性能。 在索引视图中,我无法在索引视图中使用UNIONUNPIVOTCROSS JOIN

1 个答案:

答案 0 :(得分:2)

如果您创建了一个Numbers表,基本上可以执行非法CROSS JOIN

的工作,该怎么办?
Create Table Numbers (number INT NOT NULL PRIMARY KEY) 
Go

Insert Numbers 
Select top 30000 row_number() over (order by (select 1)) as rn
from sys.all_objects s1 cross join sys.all_objects s2
go

Create view v_unpivot with schemabinding
as  
Select MyTable.ID,
        n.number as [Level],
        Case n.number
            When 1 Then MyTable.AccID1
            When 2 Then MyTable.AccID2
            Else MyTable.AccID3
        End AS AccID
From dbo.Mytable
Join dbo.Numbers n on n.number BETWEEN 1 AND 3 
go

Create unique clustered index pk_v_unpivot on v_unpivot (ID, [Level]) 
go

Select 
  ID,
  [Level],
  AccID
From v_unpivot with (noexpand)
Where AccID IS NOT NULL 
Order by ID, [Level]

WHERE AccID IS NOT NULL必须是查询的一部分,因为索引视图中不允许派生表。