Click here to Skip to main content
15,886,780 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
SQL
AS
BEGIN
WITH cte
  AS
  (
    SELECT row_number () OVER ( PARTITION BY
    BillofMaterialsId, MasterItemId, MemberItemId, MemberRevisionId  ORDER BY BillofMaterialsId DESC ) AS ROW,
    *
   FROM BOMDetails_Stg
  )
  DELETE CTE
  WHERE ROW > 1



What this code does actually please explain me.

Thanks in advance.
Posted
Comments
__TR__ 4-Jan-13 6:44am    
The sql statement is deleting duplicate rows from BOMDetails_Stg which have same BillofMaterialsId, MasterItemId, MemberItemId and MemberRevisionId
bapu_reddy 4-Jan-13 6:54am    
Thanks bro, but why CTE is used? Please explain me.
Amir Mahfoozi 4-Jan-13 7:01am    
In my opinion it was just an option. If you want to use row_number result for further operations it is necessary to use "temporary tables" or "derived tables" or "multiple CTEs" in one query statement.
__TR__ 4-Jan-13 7:22am    
As Amir said it is just an option. By using CTE you can avoid creating a temp table and if you delete a row in CTE the row gets deleted from table BOMDetails_Stg as well. You can also do it using temp tables but you will need to declare the table first, insert data into it and then delete the rows from BOMDetails_Stg using data in temp table.

1 solution

Below is the explanation

SQL
WITH cte
  AS
  (
    SELECT row_number () OVER ( PARTITION BY
    BillofMaterialsId, MasterItemId, MemberItemId, MemberRevisionId  ORDER BY BillofMaterialsId DESC ) AS ROW,
    *
   FROM BOMDetails_Stg
  )


Above code will rank duplicate values . It means if you have below data
BillofMaterialsId MasterItemId MemberItemId MemberRevisionId
AAA BBB CCC DDD
AAA BBB CCC DDD
EEE FFF GGG HHH

Then row_number () function will rank first two rows as 1 , 2 and third row as 1.
So if we want to remove duplicate from above table then we need to delete data which has rownumber as 2

SQL
DELETE CTE
 WHERE ROW > 1


If the first code WITH function will create CTE table with ROW_NUMBER as mentioned earlier . This query will remove data from actual table where ROW_NUMBER is greater than 1. Means it will remove duplicate row.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900