这是我的看法:
Create View [MyView] as
(
Select col1, col2, col3 From Table1
UnionAll
Select col1, col2, col3 From Table2
)
我需要添加一个名为Id
的新列,我需要这个列是唯一的,所以我想添加新列作为标识。我必须提到这个视图返回了大量的数据,所以我需要一个性能良好的方法,而且我还使用了两个带有union的select查询,我认为这可能有些复杂,那么你的建议是什么?
在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
视图只是一个不包含数据本身的存储查询,因此您可以添加稳定的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
)
除非满足以下条件,否则无法保证使用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
)
使用“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
)