declare @Formats TABLE
(
	FormatID int,
	Name nvarchar(50),
	Description nvarchar(255),
	StyleType int,
	DocStyle nvarchar(255)
)
insert into @Formats
select FormatID,Name,Description, 10000 + xDocStyle.value('@Index', 'int') StyleType, 
	xDocStyle.value('@Name', 'nvarchar(255)') DocStyle from Formats
	cross apply data.nodes('//DocStyle') tDocStyle(xDocStyle)
	Where xDocStyle.value('@Name', 'nvarchar(255)') like 'Document Cover%' and name like 'Wst%'

declare @DocCoverSheets Table
(
	ItemID int primary Key,
	ContentID int,
	PreviousID int,
	NextID int,
	PartContentID int
)
insert into @DocCoverSheets
select VI.ItemID, VI.ContentID, ii.PreviousID, ip.ItemID, pp.ContentID from Contents CC
JOIN VEFN_GetVersionFormatItems('') VI ON VI.ContentID = CC.ContentID
JOIN VEFN_GETVERSIONNAMES() VN ON VI.VERSIONID = VN.VERSIONID
Join @Formats FF ON FF.FormatID = VI.FormatID and CC.Type = FF.StyleType
Join Items II ON VI.ItemID = II.ItemID
Left Join Parts PP on PP.ItemID = VI.ItemID
Left Join Items IP on IP.PreviousID = VI.ItemID
Where CC.Type Between 10000 and 19999

select * from @docCoverSheets

Update TR Set TR.ToID = TT.NextID, TR.RangeID = TT.NextID
From  Transitions TR
Join @DocCoverSheets TT ON TT.ItemID = TR.TOID


-- Update Items for NextID

Update II Set PreviousID = TT.PreviousID
from Items II Join @DocCoverSheets TT ON II.ItemID = TT.NextID

-- Update Parts for PartContentID and ItemID

Update PP Set ItemID = TT.NextID
from Parts PP Join @DocCoverSheets TT ON TT.ItemID = PP.ItemID and TT.PartContentID = pp.ContentID

--Delete Doc Cover Sheet Items

Delete From tblItems where ItemID in (select ItemID from @DocCoverSheets)

