Any help that can be provided would be much appreciated.
I have the following two tables
TS_DEF_TRADER:
DEF_TRADER_ID MANAGER_CD INV_CLASS_CD TRADER_CD
------ ------- ---------- ---------
101 HARRIT EQTY MMGR_DT
108 NAIDON EQTY MMGR_DT
123 MLONDG EQTY MMGR_DT
and PDF_USER_GROUP:
GRP_CD USER_CD
------ -------
STANLIB_MULTI_MANAGER HARRIT
STANLIB_MULTI_MANAGER NAIDON
STANLIB_MULTI_MANAGER MLONDG
STANLIB_MULTI_MANAGER FARRYM
STANLIB_MULTI_MANAGER HOLMEM
What I want to do is create some kind of a looped SQL insert statement (if that's the right terminology) that will check PDF_USER_GROUP and if there is a USER_CD with GRP_CD = STANLIB_MULTI_MANAGER that is missing from TS_DEF_TRADER. If any anything is missing then it will insert the relevant row.
I've written the below statement:
declare @DefTraderID INT
declare @Mgr varchar(200)
set @DefTraderID = (select MAX(DEF_TRADER_ID) + 1 from TS_DEF_TRADER)
set @Mgr = (select min(USER_CD) from PDF_USER_GROUP where not exists
(select * from TS_DEF_TRADER where
TRADER_CD = 'MMGR_DT' and
INV_CLASS_CD = 'EQTY' and
TS_DEF_TRADER.MANAGER_CD = PDF_USER_GROUP.USER_CD)
and GRP_CD = 'STANLIB_MULTI_MANAGER' and USER_CD not in ('MMGR_DT', 'SLIB_INDEX'))
insert into TS_DEF_TRADER (DEF_TRADER_ID,MANAGER_CD,INV_CLASS_CD, TRADER_CD)
values (@DefTraderID,@Mgr, 'EQTY', 'MMGR_DT')
If I run this manually myself twice, I get the following result which is what I want:
DEF_TRADER_ID MANAGER_CD INV_CLASS_CD TRADER_CD
------ ------- ---------- ---------
101 HARRIT EQTY MMGR_DT
108 NAIDON EQTY MMGR_DT
123 MLONDG EQTY MMGR_DT
124 FARRYM EQTY MMGR_DT
125 HOLMEM EQTY MMGR_DT
If I were to run it a third time this would happen:
DEF_TRADER_ID MANAGER_CD INV_CLASS_CD TRADER_CD
------ ------- ---------- ---------
101 HARRIT EQTY MMGR_DT
108 NAIDON EQTY MMGR_DT
123 MLONDG EQTY MMGR_DT
124 FARRYM EQTY MMGR_DT
125 HOLMEM EQTY MMGR_DT
126 NULL EQTY MMGR_DT
I need it to run by itself (ie: loop) and stop once when it needs to so we don't get the NULLs.