DECLARE @ssz bit, @akineo bit, @onko bit, @prev bit

SET @ssz = (
select ParameterValue from vclib.T_HOLDER_PARAMETER 
where Holder = (select top 1 holderid from VCLib.T_HOLDER where [Name] = 'SendingToTehLabHolder')
and ParameterName = 'SendSszParam')

SET @onko = (
select ParameterValue from vclib.T_HOLDER_PARAMETER 
where Holder = (select top 1 holderid from VCLib.T_HOLDER where [Name] = 'SendingToTehLabHolder')
and ParameterName = 'SendOnkoParam')

SET @prev = (
select ParameterValue from vclib.T_HOLDER_PARAMETER 
where Holder = (select top 1 holderid from VCLib.T_HOLDER where [Name] = 'SendingToTehLabHolder')
and ParameterName = 'SendPreventionParam')

SET @akineo = (
select ParameterValue from vclib.T_HOLDER_PARAMETER 
where Holder = (select top 1 holderid from VCLib.T_HOLDER where [Name] = 'SendingToTehLabHolder')
and ParameterName = 'SendAkineoParam')

IF @akineo = 0
	BEGIN
		DELETE  sm
			from EMDR.T_SIDE_MESSAGE sm join emdr.T_EMPR empr on empr.FileID = sm.Empr
			where (empr.VMCL & 4) <> 0 
			and (CASE WHEN (@ssz = 1 and (empr.VMCL & 8) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@onko = 1 and (empr.VMCL & 1) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@prev = 1 and (empr.VMCL & 2) <> 0) THEN 0 ELSE 1 END) = 1
			and SendState = 0
	END
IF @ssz = 0
	BEGIN
		DELETE  sm
			from EMDR.T_SIDE_MESSAGE sm join emdr.T_EMPR empr on empr.FileID = sm.Empr
			where (empr.VMCL & 8) <> 0
			and (CASE WHEN (@akineo = 1 and (empr.VMCL & 4) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@onko = 1 and (empr.VMCL & 1) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@prev = 1 and (empr.VMCL & 2) <> 0) THEN 0 ELSE 1 END) = 1
			and SendState = 0
	END
IF @onko = 0
	BEGIN
		DELETE  sm
			from EMDR.T_SIDE_MESSAGE sm join emdr.T_EMPR empr on empr.FileID = sm.Empr
			where (empr.VMCL & 1) <> 0
			and (CASE WHEN (@akineo = 1 and (empr.VMCL & 4) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@ssz = 1 and (empr.VMCL & 8) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@prev = 1 and (empr.VMCL & 2) <> 0) THEN 0 ELSE 1 END) = 1
			and SendState = 0
	END
IF @prev = 0
	BEGIN
		DELETE  sm
			from EMDR.T_SIDE_MESSAGE sm join emdr.T_EMPR empr on empr.FileID = sm.Empr
			where (empr.VMCL & 2) <> 0
			and (CASE WHEN (@akineo = 1 and (empr.VMCL & 4) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@ssz = 1 and (empr.VMCL & 8) <> 0) THEN 0 ELSE 1 END) = 1
			and (CASE WHEN (@onko = 1 and (empr.VMCL & 1) <> 0) THEN 0 ELSE 1 END) = 1
			and SendState = 0
	END
GO