USE [site_fuchs] GO /****** Object: StoredProcedure [dbo].[ocms_deleteItem] Script Date: 02.12.2020 21:05:05 ******/ DROP PROCEDURE [dbo].[ocms_deleteItem] GO /****** Object: StoredProcedure [dbo].[ocms_deleteItem] Script Date: 02.12.2020 21:05:06 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE PROCEDURE [dbo].[ocms_deleteItem] @ocms_iid bigint AS BEGIN SET NOCOUNT ON; DECLARE @children TABLE([ocms_iid] bigint, [parent_iid] bigint); with cte as ( select [ocms_iid], [parent_iid] from [ocms_items] as i WHERE i.[parent_iid] = @ocms_iid --only children and below UNION ALL select i.[ocms_iid], i.[parent_iid] from [ocms_items] as i JOIN cte on cte.ocms_iid = i.[parent_iid] ) insert into @children select * from cte; --first delete childrens properties, bc else the foreign key constraint will prevent to continue */ DELETE p OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__properties] FROM [dbo].[ocms_properties] as p WHERE p.[ocms_iid] in (SELECT c.[ocms_iid] FROM @children as c); -- only children's as selected at beginning / DELETE i OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__items] FROM [ocms_items] as i WHERE i.[ocms_iid] in (SELECT c.[ocms_iid] FROM @children as c);; -- only children as selected at beginning / DELETE p OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__properties] FROM [dbo].[ocms_properties] as p WHERE p.[ocms_iid] = @ocms_iid; -- only children's as selected at beginning / DELETE FROM [ocms_items] OUTPUT deleted.*, GETUTCDATE(), null INTO [dbo].[ocms_archive__items] WHERE [ocms_iid] = @ocms_iid; SELECT TOP(1) [ocms_iid] FROM [dbo].[ocms_archive__items] WHERE [ocms_iid] = @ocms_iid; END GO ALTER AUTHORIZATION ON [dbo].[ocms_deleteItem] TO SCHEMA OWNER GO