if NOT Exists (Select * from externalreference)
BEGIN

	DECLARE @ROOTID int
	DECLARE @GROUPID INT
	DECLARE @ExtRef INT

	DECLARE #EXTREFCUR CURSOR FOR
		SELECT FK_ExternalRefID FROM ReservationExternalRefXtab
		
	OPEN #EXTREFCUR
		
	FETCH NEXT FROM #EXTREFCUR INTO @ExtRef
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO ExternalReference (Qualifier, Value)
		VALUES ('ROOT', '')	
		SELECT @ROOTID = @@IDENTITY
		
		INSERT INTO ExternalReference (ParentID, Qualifier, Value)
		VALUES (@ROOTID, 'UNIQUEID', '') 
		SELECT @GROUPID = @@IDENTITY
		
		INSERT INTO ExternalReference (ParentID, Qualifier, Value)
		VALUES (@GROUPID, 'EXTREF', CAST(@ExtRef AS VARCHAR(255))) 
		
		UPDATE ReservationExternalRefXtab
		Set FK_ExternalRefID = @ROOTID
		WHERE CURRENT OF #EXTREFCUR
		
		FETCH NEXT FROM #EXTREFCUR INTO @ExtRef
	END

	CLOSE #EXTREFCUR
	DEALLOCATE #EXTREFCUR
END
