Remove duplicates records and add unique key to the column

  • I have to  delete  duplicates records  which having  same date and same ID with below conditions and then  add unique key on date and ID 

    SELECT SDATE , ID , COUNT(1) AS CNT FROM  OT_DTL GROUP BY SDATE , ID HAVING COUNT(1)>1

    I have tried with many different ways  and google but it gives error for  delete  the  records 
    Kindly suggest on this if any one knows   or  available asap


  • WITH OrderedOT_DTL
    AS
    (
        SELECT *
            -- You may have a column value you prefer to keep. (SELECT NULL) just orders as read.
            ,ROW_NUMBER() OVER (PARTITION BY ID, SDATE ORDER BY (SELECT NULL)) AS rn
        FROM OT_DTL
    )
    DELETE OrderedOT_DTL
    WHERE rn > 1;
    GO
    ALTER TABLE OT_DTL
    ADD CONSTRAINT UQ_OT_DTL_ID_SDATE UNIQUE (ID, SDATE);
    GO

  • Thank you so much, this code is working properly .

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply