DDL:
Script:
The insert at the top of the script puts a 158 s_code into table_b that is then merged into table_a as expected. However, if I then change the s_code to 160 and reprocess I was expecting to see the initially inserted row deleted by the delete clause at the end of the script.
However, the only way I can get the delete to work and also update if processing another 158 is by changing the scrip as follows:
The original script reads to me:
If it is 158 and doesn't exist insert it
If its 158 and it does exist update it
If its 160 delete it
However, the merge doesn't seem to be working in this way !!!
Can anyone explain what I am doing wrong.
Many thanks
[blue]DBomrrsm[/blue]
[blue]Software code, like laws and sausages, should never be examined in production[/blue][black] - [/black][purple]Edward Tenner[/purple]
Code:
CREATE TABLE table_a ( pid VARCHAR2(13), d_code VARCHAR2(3), s_date DATE);
CREATE TABLE table_b (pid VARCHAR2(13), d_code VARCHAR2(3), s_date DATE , s_code VARCHAR2(3),m_s VARCHAR2(1));
Script:
Code:
insert into table_b (pid,d_code,s_date,s_code,m_s) values('dave_bell_upi','001',sysdate,'158','P');
MERGE INTO table_a a
USING (SELECT b.pid, b.d_code, b.s_date, b.s_code
FROM table_b b
WHERE b.m_s = 'P' AND b.s_code IN ('158', '160')) x
ON (a.pid = x.pid)
WHEN NOT MATCHED THEN
INSERT (a.pid, a.d_code, a.s_date)
VALUES (x.pid, x.d_code, x.s_date)
WHERE x.s_code = '158'
WHEN MATCHED THEN
UPDATE
SET a.d_code = x.d_code, a.s_date = x.s_date
WHERE x.s_code = '158'
DELETE
WHERE (x.s_code = '160');
delete from table_b;
commit;
However, the only way I can get the delete to work and also update if processing another 158 is by changing the scrip as follows:
Code:
insert into table_b (pid,d_code,s_date,s_code,m_s) values('dave_bell_upi','001',sysdate,'160','P');
MERGE INTO table_a a
USING (SELECT b.pid, b.d_code, b.s_date, b.s_code
FROM table_b b
WHERE b.m_s = 'P' AND b.s_code IN ('158', '160')) x
ON (a.pid = x.pid)
WHEN NOT MATCHED THEN
INSERT (a.pid, a.d_code, a.s_date)
VALUES (x.pid, x.d_code, x.s_date)
WHERE x.s_code = '158'
WHEN MATCHED THEN
UPDATE
SET a.d_code = x.d_code, a.s_date = x.s_date
WHERE x.s_code in ( '158','160')
DELETE
WHERE (x.s_code = '160');
delete from table_b;
commit;
The original script reads to me:
If it is 158 and doesn't exist insert it
If its 158 and it does exist update it
If its 160 delete it
However, the merge doesn't seem to be working in this way !!!
Can anyone explain what I am doing wrong.
Many thanks
[blue]DBomrrsm[/blue]
[blue]Software code, like laws and sausages, should never be examined in production[/blue][black] - [/black][purple]Edward Tenner[/purple]