将Identity列添加到SQL Server 2008中的视图

问题描述 投票:12回答:4

这是我的看法:

Create View [MyView] as
(
Select col1, col2, col3 From Table1
UnionAll
Select col1, col2, col3 From Table2
)

我需要添加一个名为Id的新列,我需要这个列是唯一的,所以我想添加新列作为标识。我必须提到这个视图返回了大量的数据,所以我需要一个性能良好的方法,而且我还使用了两个带有union的select查询,我认为这可能有些复杂,那么你的建议是什么?

sql sql-server sql-server-2008 tsql view
4个回答
24
投票

在SQL Server 2008中使用ROW_NUMBER()函数。

Create View [MyView] as

SELECT ROW_NUMBER() OVER( ORDER BY col1 ) AS id, col1, col2, col3
FROM(
    Select col1, col2, col3 From Table1
    Union All
    Select col1, col2, col3 From Table2 ) AS MyResults
GO

3
投票

视图只是一个不包含数据本身的存储查询,因此您可以添加稳定的ID。如果您需要用于其他目的的id,例如分页,您可以执行以下操作:

create view MyView as 
(
    select row_number() over ( order by col1) as ID, col1 from  (
        Select col1 From Table1
        Union All
        Select col1 From Table2
    ) a
)

2
投票

除非满足以下条件,否则无法保证使用ROW_NUMBER()的查询返回的行与每次执行的顺序完全相同:

  1. 分区列的值是唯一的。 [分区是亲子,像老板有3名员工] [忽略]
  2. ORDER BY列的值是唯一的。 [如果第1列是唯一的,row_number应该是稳定的]
  3. 分区列和ORDER BY列的值的组合是唯一的。 [如果您的订单中需要10列才能获得独特...请将其设置为使row_number稳定]

这里有一个次要问题,这是一个观点。 Order By不总是在视图中工作(长期sql bug)。忽略row_number()一秒钟:

create view MyView as 
(
    select top 10000000 [or top 99.9999999 Percent] col1 
    from  (
        Select col1 From Table1
        Union All
        Select col1 From Table2
    ) a order by col1
)

0
投票

使用“row_number()over(按col1排序)作为ID”是非常昂贵的。这种方式在成本上更有效:

Create View [MyView] as
(
    Select ID = isnull(cast(newid() as varchar(40)), '')
           , col1
           , col2
           , col3 
    From Table1
    UnionAll
    Select ID = isnull(cast(newid() as varchar(40)), '')
           , col1
           , col2
           , col3 
    From Table2
)
© www.soinside.com 2019 - 2024. All rights reserved.