CREATE TABLE #tmpclass
	(
		Id INT IDENTITY,
		DigitalFormId INT,
		SourceTypeId SMALLINT,
		SourceId BIGINT
	)

CREATE TABLE #tmpDivision
	(
		Id INT IDENTITY,
		DigitalFormId INT,
		SourceId BIGINT,
		SourceTypeId SMALLINT
	)

IF EXISTS(SELECT TOP 1 1 FROM [sStudent].[tTempDigitalFormScopeHistory])
BEGIN
	INSERT INTO [sStudent].[tDigitalFormScope]
	SELECT * FROM [sStudent].[tTempDigitalFormScopeHistory] WHERE SourceTypeId IN (2016,2017)
END
ELSE 
BEGIN
	INSERT INTO [sStudent].[tTempDigitalFormScopeHistory]
	SELECT * FROM [sStudent].[tDigitalFormScope]
END
	
	INSERT INTO #tmpClass
	SELECT * FROM sStudent.tDigitalFormScope 
	WHERE DigitalFormId IN (SELECT ID FROM [sStudent].[tDigitalForm]) AND SourceTypeId IN (2016,2017)
	
	DECLARE @lCount INT
	DECLARE @lSourceTypeId INT,@lDigitalFormId INT,@lSourceId BIGINT
	SELECT @lCount =  COUNT(Id) FROM #tmpClass
	
	WHILE @lCount > 0 
	BEGIN
		SET @lSourceTypeId = (SELECT SourcetypeId FROM #tmpClass WHERE Id = @lCount)
		SET @lDigitalFormId = (SELECT DigitalFormId FROM #tmpClass WHERE Id = @lCount)
		SET @lSourceId = (SELECT SourceId FROM #tmpClass WHERE Id = @lCount)
	
		IF(@lSourceTypeId=2017)
		BEGIN
			INSERT INTO #tmpDivision
			SELECT @lDigitalFormId, Id AS SourceId, 2016 FROM sSetup.tClassMaster WHERE DepartmentId = @lSourceId
		END
	
		ELSE
		BEGIN
			INSERT INTO #tmpDivision
			SELECT DigitalFormId,SourceId,SourceTypeId FROM #tmpClass WHERE SourceID = @lSourceId
		END
		SET @lCount = @lCount - 1
	END	
	
	DECLARE @lCount1 INT
	DECLARE @lDigitalFormId1 INT,@lSourceId1 BIGINT
	SELECT @lCount1 =  COUNT(Id) FROM #tmpDivision
	
	WHILE @lCount1 > 0 
	BEGIN
		SET @lDigitalFormId1 = (SELECT DigitalFormId FROM #tmpDivision WHERE Id = @lCount1)
		SET @lSourceId1 = (SELECT SourceId FROM #tmpDivision WHERE Id = @lCount1)
	
		IF NOT EXISTS(SELECT 1 FROM sStudent.tDigitalFormScope WHERE DigitalFormId=@lDigitalFormId1 AND SourceTypeID = 2005 AND SourceId =@lSourceId1)
		BEGIN
			print 1
			INSERT INTO sStudent.tDigitalFormScope 
			SELECT @lDigitalFormId1,2005,Id AS SourceId FROM sSetup.tDivisionMaster WHERE ClassId = @lSourceId1
		END
		SET @lCount1 = @lCount1 - 1
	END
	
DELETE FROM sStudent.tDigitalFormScope WHERE SourceTypeId IN (2016,2017)
DROP TABLE  #tmpDivision
DROP TABLE #tmpclass