I currently have 2 tables as follows:
CREATE TABLE [CRPDTA].[F55MRKT119]
(
mhan8 int,
mhac02 varchar(5),
mhmot varchar(5),
mhupmj int
)
GO
CREATE TABLE [CRPDTA].[F55MRKT11]
(
mdan8 int,
mdac02 varchar(5),
mdmot varchar(5),
mdmail int,
mdmag int,
mdupmj int
)
What I would like to do is place a trigger on F55MRKT119 which will
insert records to the F55MRKT11 if they do not exist in that table
based on the [mdan8] field. If the record does exist I would like
Update the corresponding record and increment either the [MDMAIL] or
the [MDMAG] based on the inserted [MHMOT]. What I have so far is as
follows:
TRIGGER #1:
CREATE TRIGGER trgIns_Summary ON [CRPDTA].[F55MRKT119]
FOR INSERT
AS
BEGIN
INSERT INTO CRPDTA.F55MRKT11
select INS.MHAN8, INS.MHAC02, INS.MHMOT,
case when INS.MHMOT='MAG' then 0 ELSE 1 end,
case when INS.MHMOT='MAG' then 1 ELSE 0 end,
'0' from INSERTED INS
WHERE ins.mhan8 not in(select mdan8 from crpdta.f55MRKT11)
END
TRIGGER #2:
CREATE TRIGGER trgUpd_Summary ON [CRPDTA].[F55MRKT119]
FOR Update
AS
BEGIN
UPDATE CRPDTA.F55MRKT11
SET MDMAIL= case when INS.MHMOT='MAG' then 0+MDMAIL
when INS.MHMOT<>'MAG' then 1+MDMAIL end,
MDMAG= case when INS.MHMOT='MAG' then 1+MDMAG
when INS.MHMOT<>'MAG' then 0+MDMAG end
from INSERTED INS JOIN CRPDTA.F55MRKT11
on(ins.mhan8=mdan8)
END
For instance if I do the following insert:
INSERT INTO CRPDTA.F55MRKT119
VALUES('212131','VK4','AL4','0')
then
INSERT INTO CRPDTA.F55MRKT119
VALUES('212131','VK4','MAG','0')
This is what I expect in both tables:
[CRPDTA.F55MRKT119] (2 Records)
MHAN8 MHAC02 MHMOT MHUPMJ
------ ------ ----- ------
212131 VK4 AL4 0
212131 VK4 MAG 0
[CRPDTA.F55MRKT11] (1 Record)
MDAN8 MDAC02 MDMOT MDMAIL MDMAG MDUPMJ
----- ------ ----- ------ ----- ------
212131 VK4 AL4 1 1 0
The insert part works fine in that it iserts in both tables with the
correct values. However it seems as if the Update protion is failing
for some reason. WHat I have tried so far is setting the trigger order
for the update to run first and vice-versa, but still no luck. Any
help would be appreciated.