﻿CREATE PROCEDURE [dbo].[sp_TestSetupsDeleteManyByDate]
         @DeleteDateBefore  DATETIME = NULL,
		 @errorNumber		INT OUTPUT,
		 @errorMessage		NVARCHAR(255) OUTPUT
AS
BEGIN
	SET @errorNumber = 0; 	
	SET @errorMessage = SPACE(0);
	BEGIN TRY
	BEGIN TRANSACTION [tDeleteTestSetupsMany]
					
		DELETE TSOMD FROM [dbo].[TestSetupObjectMetaData] AS TSOMD
		INNER JOIN [DataPro].[dbo].[TestSetups] TS ON TSOMD.TestSetupId = TS.TestSetupId 
		WHERE TS.LastModified < @DeleteDateBefore

		DELETE TSH FROM [dbo].[TestSetupHardware] AS TSH
		INNER JOIN [DataPro].[dbo].[TestSetups] TS ON TSH.TestSetupId = TS.TestSetupId 
		WHERE TS.LastModified < @DeleteDateBefore

	    DELETE LT FROM [dbo].[LevelTriggers] AS LT
		INNER JOIN [DataPro].[dbo].[TestSetups] TS ON LT.TestSetupId = TS.TestSetupId 
		WHERE TS.LastModified < @DeleteDateBefore

	    DELETE CC FROM [dbo].[CalculatedChannels] AS CC
		INNER JOIN [DataPro].[dbo].[TestSetups] TS ON CC.TestSetupId = TS.TestSetupId 
		WHERE TS.LastModified < @DeleteDateBefore

		DELETE TG FROM [dbo].[TestGraphs] AS TG
		INNER JOIN [DataPro].[dbo].[TestSetups] TS ON TG.TestSetupId = TS.TestSetupId 
		WHERE TS.LastModified < @DeleteDateBefore

		/*Delete group channel settings*/		

		DELETE GCS FROM [dbo].[GroupChannelSettings] AS GCS
		INNER JOIN [dbo].[Channels] AS C ON GCS.ChannelId=C.Id 
		INNER JOIN [dbo].[Groups] AS G ON C.GroupId=G.Id 
		INNER JOIN [dbo].TestSetupGroups AS TSG ON G.Id=TSG.GroupId
		INNER JOIN [dbo].[TestSetups] TS ON TSG.TestSetupId = TS.TestSetupId
		WHERE TS.LastModified < @DeleteDateBefore 
		
		
		/*Delete group hardware*/
		DELETE GH FROM [dbo].[GroupHardware] AS GH
		INNER JOIN [dbo].[TestSetupGroups] AS TSG ON GH.GroupId=TSG.GroupId
		INNER JOIN [dbo].[TestSetups] TS ON TSG.TestSetupId = TS.TestSetupId
		WHERE TS.LastModified < @DeleteDateBefore 
		
		/*Delete group channels*/
		DELETE C FROM [dbo].[Channels] AS C
		INNER JOIN [dbo].[TestSetupGroups] AS TSG ON C.GroupId = TSG.GroupId 
		INNER JOIN [dbo].[TestSetups] TS ON TSG.TestSetupId = TS.TestSetupId
		WHERE TS.LastModified < @DeleteDateBefore 
		
		
		/*grab a copy of all groups associated with test so we can delete them*/
		
		SELECT [GroupId] INTO #temptable 
		FROM  [DataPro].[dbo].[TestSetupGroups] AS TSG
		INNER JOIN [DataPro].[dbo].[TestSetups] TS ON TSG.TestSetupId = TS.TestSetupId
		WHERE TS.LastModified <  @DeleteDateBefore

		/*unassociate the group from the test setup*/
		
		DELETE TSG FROM [dbo].[TestSetupGroups] AS TSG 
		INNER JOIN [dbo].[TestSetups] TS ON TSG.TestSetupId = TS.TestSetupId
		WHERE TS.LastModified < @DeleteDateBefore 
		
		/*delete the groups*/
		DELETE FROM [dbo].[Groups] WHERE [Id] IN (SELECT [GroupId] FROM #tempTable)

		DELETE TS FROM [dbo].[TestSetups] TS 
		WHERE TS.LastModified < @DeleteDateBefore 
	
		COMMIT TRANSACTION [tDeleteTestSetupsMany]

	END TRY
	BEGIN CATCH
		SET @errorNumber = error_number()
		SET @errorMessage = error_message()
		ROLLBACK TRANSACTION [tDeleteTestSetupsMany]
	END CATCH
END

