-- EXEC MIG_DATASET_SEQ_INFO_Sp
CREATE OR ALTER PROCEDURE MIG_DATASET_SEQ_INFO_Sp
AS
BEGIN
	DELETE FROM MIG_DATASET_SEQ_INFO

	INSERT INTO [MIG_DATASET_SEQ_INFO]
	(
		 [ZZ_ID]
		,[DSET_KEY]
		,[REVISION]
        ,[I_SEQUENCE]
	)
	SELECT 
		FIL.ZZ_ID, 
		FIL.DSET_KEY,
		FIL.REVISION,
		CASE WHEN DOC.ZZ_ID IS NULL THEN '0' ELSE MIG_DOC_SEQ_INFO.I_SEQUENCE END AS "SequenceNumber"
	FROM DATASET FIL
	LEFT JOIN DOC_DATASET
	  ON DOC_DATASET.DSET_KEY = FIL.DSET_KEY
	 AND DOC_DATASET.DSET_REVISION = FIL.REVISION
	LEFT JOIN DOC
	  ON DOC.DOC_KEY = DOC_DATASET.DOC_KEY
	 AND DOC.REVISION = DOC_DATASET.REVISION
	LEFT JOIN MIG_DOC_SEQ_INFO
	  ON MIG_DOC_SEQ_INFO.ZZ_ID = DOC.ZZ_ID
	WHERE FIL.OBJECT_TYPE IN (12, 14)
END
