If it has to be a trigger, code you wrote was close; it is just that nothing is equal to null
. You can't check whether card_no = null
, but whether card_no is null
.
As of rest of your code, several objections:
- in trigger, use
when
clause instead of if-then-else
- when performing insert, always specify column names you're inserting data into. The way you did it, it is impossible to know which value represents what
- moreover, it seems that you're inserting date value. If that's so, then don't insert a string (that's what
'01-FEB-2023'
is) and don't rely on implicit datatype conversion. If NLS settings change, you'll get an error (which one? It depends on those settings). Insert proper date datatype value instead, either as date literal (which is what I did in example that follows), or use to_date
function with appropriate format model
As you didn't provide table description, I'll guess.
SQL> create table orders
2 (order_id number,
3 col2 number,
4 order_date date,
5 status varchar2(5),
6 payment varchar2(10),
7 card_no varchar2(10),
8 col7 number);
Table created.
Trigger:
SQL> create or replace trigger check_card_info
2 before insert on orders
3 for each row
4 when (new.payment = 'card' and new.card_no is null)
5 begin
6 raise_application_error(-20002, 'card info is missing');
7 end;
8 /
Trigger created.
Testing: invalid row first (card_no is missing):
SQL> insert into orders (order_id, col2, order_date, status, payment, card_no, col7)
2 values (21200122, 11, date '2023-02-01', 'no', 'card', null, 150);
insert into orders (order_id, col2, order_date, status, payment, card_no, col7)
*
ERROR at line 1:
ORA-20002: card info is missing
ORA-06512: at "SCOTT.CHECK_CARD_INFO", line 2
ORA-04088: error during execution of trigger 'SCOTT.CHECK_CARD_INFO'
Valid row:
SQL> insert into orders (order_id, col2, order_date, status, payment, card_no, col7)
2 values (21200122, 11, date '2023-02-01', 'no', 'card', 'Card 123', 150);
1 row created.
SQL>