SQL Server 2008 R2: Delete duplicate rows from tables containing in view

前端 未结 4 517
孤街浪徒
孤街浪徒 2021-01-17 02:45

--Creating Table dup1

CREATE TABLE dup1
(
    cola VARCHAR(10),
    colb VARCHAR(10)
);

--Insertion of records

INSERT INTO          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 02:53

    Are dup1 and dup2 partitionable table? I mean if you can add a column to them that allows to understand wich table to update. e.g. date so that if you insert a date in an interval you update dup1 else dup2. If you don't have a partitioning column you could create one simply adding a column able to identify the table (e.g. a varchar(1) with value '1' or an int having value 1 for dup1 and 2 for dup2) . This column should be a part of the primary key (here I created an ID). The table could look like this:

    CREATE TABLE dbo.dup1
        (
        cola   VARCHAR (10),
        colb   VARCHAR (10),
        ID     INT IDENTITY NOT NULL,
        partit NCHAR (10) CONSTRAINT DF_dup1_partit DEFAULT ('1') NOT NULL CONSTRAINT CK_dup1 CHECK ([PARTIT]='1'),
        CONSTRAINT PK_dup1 PRIMARY KEY (ID, partit)
        )
    
    CREATE TABLE dbo.dup2
        (
        cola   VARCHAR (10),
        colb   VARCHAR (10),
        ID     INT IDENTITY NOT NULL,
        partit NCHAR (10) CONSTRAINT DF_dup2_partit DEFAULT ('2') NOT NULL CONSTRAINT CK_dup2 CHECK ([PARTIT]='2'),
        CONSTRAINT PK_dup2 PRIMARY KEY (ID, partit)
        )
    

    So that the view will be:

    CREATE VIEW V_Dup as
    SELECT * FROM dup1 UNION ALL 
    SELECT * FROM dup2
    WITH CHECK OPTION
    

    this way you will be able to use the code I posted before

提交回复
热议问题