ALTER PROCEDURE [dbo].[sp_DASDelete]
	@Id					INT = NULL,
	@SerialNumber		NVARCHAR (50) = NULL,
	@Embedded           BIT=0,
	@errorNumber		INT OUTPUT,
	@errorMessage		NVARCHAR (255) OUTPUT
AS
BEGIN
	SET NOCOUNT ON;
	SET @errorNumber=0
	SET @errorMessage=''
	
	ALTER TABLE [dbo].[Channels] NOCHECK CONSTRAINT [FK_Channels_DASId]
	ALTER TABLE [dbo].[Channels] NOCHECK CONSTRAINT [FK_Channels_SensorId]

	IF(@Id IS NULL)
	BEGIN
		IF NULLIF(@SerialNumber, '') IS NULL
		BEGIN
			SET @errorNumber = 1
			SET @errorMessage = 'Serial number or Id required'
		END	
		ELSE
		BEGIN
		SELECT @Id from [dbo].[DAS] WHERE [SerialNumber]=@SerialNumber
		IF (@Embedded = 0 )
			BEGIN
				UPDATE [dbo].[Channels] SET [DASId] = NULL, [DASChannelIndex]=NULL WHERE [DASId]=@Id
			END
		ELSE
			BEGIN
				 DELETE A FROM [dbo].[LevelTriggers] AS A INNER JOIN [dbo].[Channels] AS B on A.ChannelId = B.Id WHERE B.[DASId]=@Id
			     DELETE A FROM [dbo].[GroupChannelSettings] AS A INNER JOIN [dbo].[Channels] AS B on A.ChannelId = B.Id WHERE B.[DASId]=@Id
			     DELETE FROM [dbo].[Channels] WHERE [DASId]=@Id
			END
		DELETE FROM [dbo].[TestSetupHardware] WHERE [DASId]=@Id
		DELETE FROM [dbo].[GroupHardware] WHERE [DASId]=@Id
		DELETE FROM [dbo].[DASChannels] WHERE [DASId]=@Id		
		DELETE FROM [dbo].[DAS] WHERE [DASId] = @Id
		END			
	END
	ELSE
	BEGIN
		IF (@Embedded = 0 )
			BEGIN
				UPDATE [dbo].[Channels] SET [DASId] = 0, [DASChannelIndex]=0 WHERE [DASId]=@Id
			END
		ELSE
			BEGIN
			     DELETE A FROM [dbo].[LevelTriggers] AS A INNER JOIN [dbo].[Channels] AS B on A.ChannelId = B.Id WHERE B.[DASId]=@Id
			     DELETE A FROM [dbo].[GroupChannelSettings] AS A INNER JOIN [dbo].[Channels] AS B on A.ChannelId = B.Id WHERE B.[DASId]=@Id
			     DELETE FROM [dbo].[Channels] WHERE [DASId]=@Id
			END
		DELETE FROM [dbo].[TestSetupHardware] WHERE [DASId]=@Id
		DELETE FROM [dbo].[GroupHardware] WHERE [DASId]=@Id
		DELETE FROM [dbo].[DASChannels] WHERE [DASId]=@Id		
		DELETE FROM [dbo].[DAS] WHERE [DASId] = @Id
	END
	
	ALTER TABLE [dbo].[Channels] CHECK CONSTRAINT [FK_Channels_DASId]
	ALTER TABLE [dbo].[Channels] CHECK CONSTRAINT [FK_Channels_SensorId]

	IF(@@error != 0)
	BEGIN
		SET @errorNumber = error_number()
		SET @errorMessage = error_message()
	END
END