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 do1. update @tApplicant set myCategory='A',if myID exists in @tMySPM and @tApplicant(myCategory) is null2. update @tApplicant set myCategory='B',if myID exists in @tMySTPM and @tApplicant(myCategory) is null3. update @tApplicant set myCategory=null,if myID not exists in @tMySPM / @tSTPM and @tApplicant(myCategory) is nullMy expected result,myID | myCategory-----------------------------1925 A4474 B8398 B4656 A2288 A4876 NULL
Really need help. I'm stuckSo far, my T-SQL as following,update @tApplicant set myCategory = (if exists(t2.myID) Begin'A'Endelse if exists(t3.myID) Begin'B'Endelse NULL end)from @tApplicant t1inner join @tMySPM t2 on t1.myID=t2.myIDinner join @tMySTPM t3 on t1.myID=t3.myID