Home SQL Server How to Delete Parent Child Hierarchy Relation In SQL Server Using CTE
How to Delete Parent Child Hierarchy Relation In SQL Server Using CTE

You can delete the parent child hierarcy relation in SQL Server using the script below. It uses CTE first to delete the require records then it delete those record with the delete statement.

CREATE PROCEDURE [dbo].[prEntityLibraryDelete]

    (@LibraryID varchar(200))

AS

BEGIN

 

--DECLARE @LibraryID int

--set @LibraryID = 7;

 

WITH [CTE](LibraryID, [Name], Description, LibraryLevel, LibraryParentID, LibraryTypeID)

AS (

        SELECT LibraryID, [Name], Description, LibraryLevel, LibraryParentID, LibraryTypeID

        FROM [tblEntityLibrary] c

        WHERE (c.LibraryID = @LibraryID)

 

        UNION ALL

 

        SELECT c.*

            FROM [tblEntityLibrary] c INNER JOIN [CTE] p ON c.LibraryParentID = p.LibraryID        

)

 

DELETE FROM [tblEntityLibrary]

WHERE LibraryID IN(

    SELECT TOP 100 PERCENT t.LibraryID

    FROM [CTE] t

    ORDER BY t.LibraryLevel DESC)

 

OPTION ( MAXRECURSION 0 )

END



Comments (0)
Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:D:angry::angry-red::evil::idea::love::x:no-comments::ooo::pirate::?::(
:sleep::););)):0
Security
Please input the anti-spam code that you can read in the image.

"