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

2021-09-10 00:00:00 sql tsql sql-server-2008 sql-server view

这是我的观点:

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

我需要添加一个名为 Id 的新列,我需要这个列是唯一的,所以我想添加新列作为身份.我必须提到这个视图返回了大量数据,所以我需要一种具有良好性能的方法,而且我使用了两个带有联合的选择查询,我认为这可能有些复杂,那么您的建议是什么?

I need to add a new column named Id and I need to this column be unique so I think to add new column as identity. I must mention this view returned a large of data so I need a way with good performance, And also I use two select query with union all I think this might be some complicated so what is your suggestion?

推荐答案

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

Use the ROW_NUMBER() function in SQL Server 2008.

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

相关文章