简体   繁体   中英

DELETE clause in MERGE statement

I have a table as follow.

Name         Null         Type          
-----------  --------     -------------- 
EMPLOYEEID   **NOT NULL** NUMBER         
NAME         **NOT NULL** VARCHAR2(1000) 
AGE          *NOT NULL*   NUMBER         
SALARY                    NUMBER        
DELETEDFLAG               NUMBER(1) 

I wrote the MERGE statement to insert, update, delete records as below.

MERGE INTO EMPLOYEE tgt USING  (
SELECT( SELECT EMPLOYEE.rowId as rid  from EMPLOYEE WHERE employeeid = 70) as rid from dual ) src ON (tgt.rowid = src.rid)
WHEN MATCHED THEN UPDATE SET  name = 'PSS', age = 25, salary = 2589
WHERE employeeid = 70
DELETE WHERE DELETEDFLAG = 1
WHEN NOT MATCHED THEN
INSERT (employeeId, name, age, salary, deletedFlag) VALUES( 70, 'TSS', 28, 15000, 0);

I am facing the problem while DELETING the record. I want to delete the records when I receive the null values for name, name and salary and the deleteFlag is zero. I know only the employeeID. The MERGE query as below.

MERGE INTO EMPLOYEE tgt USING  (
SELECT( SELECT EMPLOYEE.rowId as rid  from EMPLOYEE WHERE employeeid = 70) as rid from dual ) src ON (tgt.rowid = src.rid)
WHEN MATCHED THEN UPDATE SET  name = null, age = null, salary = null
WHERE employeeid = 70
DELETE WHERE DELETEDFLAG = 0
WHEN NOT MATCHED THEN
INSERT (employeeId, name, age, salary, deletedFlag) VALUES( 70, null, null, null, 0);

The problem I faced is in this scenario it tries to update the records. The name is not null able column but it tries to update with the null. So got the SQL error.

cannot update (%s) to NULL

If I pass the not null value it works as expected.

Can anyone please advise how can I handle this scenario?

Change predicats in update sections to this

WHERE employeeid = 70 and DELETEDFLAG <> 0

If DELETEDFLAG can be null I assume you know how to change predicate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM