My tables and data as following,
declare @tApplicant table (myID varchar(200), myCategory varchar(10) null);
insert into @tApplicant(myID) values('1925');
insert into @tApplicant(myID) values('4474');
insert into @tApplicant(myID) values('8398');
insert into @tApplicant(myID) values('4656');
insert into @tApplicant(myID) values('2288');
insert into @tApplicant(myID) values('4876');
/* myID is unique */
declare @tMySPM table (myID varchar(200), subjectCd varchar(10));
insert into @tMySPM values('1925','99');
insert into @tMySPM values('1925','19');
insert into @tMySPM values('2288','78');
insert into @tMySPM values('2288','99');
insert into @tMySPM values('4656','72');
/* Combination of myID and subjectCd is unique */
declare @tMySTPM table (myID varchar(200), subjectCd varchar(10));
insert into @tMySTPM values('4474','99');
insert into @tMySTPM values('4474','19');
insert into @tMySTPM values('2288','78');
insert into @tMySTPM values('2288','99');
insert into @tMySTPM values('8398','72');
/* Combination of myID and subjectCd is unique */
What I would do
1. update @tApplicant set myCategory='A',
if myID exists in @tMySPM and @tApplicant(myCategory) is null
2. update @tApplicant set myCategory='B',
if myID exists in @tMySTPM and @tApplicant(myCategory) is null
3. update @tApplicant set myCategory=null,
if myID not exists in @tMySPM / @tSTPM and @tApplicant(myCategory) is null
My expected result,
myID | myCategory
-----------------------------
1925 A
4474 B
8398 B
4656 A
2288 A
4876 NULL
Really need help. I'm stuck
So far, my T-SQL as following,
update @tApplicant
set myCategory =
(if exists(t2.myID)
Begin
'A'
End
else if exists(t3.myID)
Begin
'B'
End
else NULL
end)
from @tApplicant t1
inner join @tMySPM t2 on t1.myID=t2.myID
inner join @tMySTPM t3 on t1.myID=t3.myID