I have this working code. Every time I ran INSERT INTO "HR"."CITY" (CITY_ID) VALUES (0); the data in CITY_ID will increase by one like this CT0001, CT0002 ... CT0015.
CREATE TABLE "HR"."CITY"
(
"CITY_ID" VARCHAR2(40 BYTE)
) ;
CREATE OR REPLACE TRIGGER "HR"."PK_MAX_TRIGGER_CITY"
BEFORE INSERT ON CITY
FOR EACH ROW
DECLARE
CNT NUMBER;
PKV CITY.CITY_ID%TYPE;
NO NUMBER;
BEGIN
SELECT COUNT(*)INTO CNT FROM CITY;
IF CNT=0 THEN
PKV:='CT0001';
ELSE
SELECT 'CT'||LPAD(MAX(TO_NUMBER(SUBSTR(CITY_ID,3,LENGTH(CITY_ID)))+1),4,'0') INTO PKV
FROM CITY;
END IF;
:NEW.CITY_ID:=PKV;
END;
/
ALTER TRIGGER "HR"."PK_MAX_TRIGGER_CITY" ENABLE;
What I want to do is this E1, E2 ... E15.
I change the code to:
IF CNT=0 THEN
PKV:='E1';
ELSE
SELECT 'E'||LPAD(MAX(TO_NUMBER(SUBSTR(CITY_ID,3,LENGTH(CITY_ID)))+1),4,'0') INTO PKV
It work at first adding E1 to database but not the second time. What inside the bracket is just to hard for me to digest. I was hoping anyone here could explain to me what actually happen in the bracket and helping me to solve this thing.
Thanks in advance.
What you need to do is to modify your Else part query .
Explaination
Whenever you want to find what is happening in the brackets start with the inner bracket .
Here,you will extract the string after
E,whereEalways there in 1st position ,so we will find the string from the2nd position.Then
–this is converting the string into number.Then it will find the max number from the table CITY,and add 1 after that
And finally appending the constant
Ewith the result .But take my suggestion ,create a sequence
city_id_seq,this will be better solution than what you are doing now.