Я считаю, что вам нужно что-то вроде этого:
select *
from @TempTable1 t1
join @TempTable2 t2 on t1.ControlNo = t2.ControlNo
where t1.Premium <> 0
and (
(@reasonID is null)
or
(@reasonID = 1 and t2.reasonID = 211)
or
(@reasonID = 2 and (t2.reasonID <> 211 or t2.reasonID is null))
)
Данные:
declare @TempTable1 table (ControlNo int,PolicyNumber varchar(50), Premium money)
insert into @TempTable1 values (1,'Pol1', 100),
(2,'Pol2', 0),
(3,'Pol3', 50),
(4,'Pol4', 0),
(5,'Pol5', 70),
(6,'Pol6', 0),
(7, 'Pol7',30),
(8, 'Pol8',10)
declare @TempTable2 table (ControlNo int,PolicyNumber varchar(50), reasonID int)
insert into @TempTable2 values (1,'Pol1', 5),
(2,'Pol2', NULL),
(3,'Pol3', 211),
(4,'Pol4', 8),
(5,'Pol5', 211),
(6,'Pol6', NULL),
(7,'Pol7',3),
(8,'Pol8',null)
Для @reasonID = null
:
ControlNo PolicyNumber Premium ControlNo PolicyNumber reasonID
----------- ------------ --------------------- ----------- ------------ -----------
1 Pol1 100.00 1 Pol1 5
3 Pol3 50.00 3 Pol3 211
5 Pol5 70.00 5 Pol5 211
7 Pol7 30.00 7 Pol7 3
8 Pol8 10.00 8 Pol8 NULL
Для @reasonID = 1
:
ControlNo PolicyNumber Premium ControlNo PolicyNumber reasonID
----------- ------------ --------------------- ----------- ------------ -----------
3 Pol3 50.00 3 Pol3 211
5 Pol5 70.00 5 Pol5 211
Для @reasonID = 2
:
ControlNo PolicyNumber Premium ControlNo PolicyNumber reasonID
----------- ------------ --------------------- ----------- ------------ -----------
1 Pol1 100.00 1 Pol1 5
7 Pol7 30.00 7 Pol7 3
8 Pol8 10.00 8 Pol8 NULL