且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2008 R2:从包含在视图中的表中删除重复行

更新时间:2023-01-29 17:21:55

create temp.表:

create temp. table :

DECLARE @tempDuplicateTable AS TABLE(
    cola VARCHAR(10),
    colb VARCHAR(10)
)

插入重复行:

INSERT INTO @tempDuplicateTable
    ( cola, colb )
    (
        SELECT a.cola, a.colb FROM dup1 a
        INNER JOIN dup2 b ON b.cola = a.cola AND b.colb = a.colb
    )

从表 dup1 和 dup2 中删除重复数据:

delete duplicate data from both table dup1 and dup2 :

DELETE a FROM dup1 a INNER JOIN @tempDuplicateTable b ON b.cola = a.cola AND b.colb = a.colb
DELETE a FROM dup2 a INNER JOIN @tempDuplicateTable b ON b.cola = a.cola AND b.colb = a.colb

如果你只是想要这个结果:

if you just want this result :

 cola   colb
   1    2
   1    3
   1    4
   1    5
   2    3
   2    4

试试这个查询:

SELECT DISTINCT * FROM V_Dup 

或者你可以像这样修改你的视图:

or you can modify your View like this :

CREATE VIEW V_Dup as
    SELECT DISTINCT a.* FROM (
    SELECT * FROM dup1 UNION ALL 
    SELECT * FROM dup2
) a