Reputation: 1543
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.
Upvotes: 0
Views: 113
Reputation: 6338
What you need to do is to modify your Else part query .
SELECT 'E'||(MAX(TO_NUMBER(SUBSTR(CITY_ID,2))+1)) INTO PKV
FROM CITY;
Explaination Whenever you want to find what is happening in the brackets start with the inner bracket .
See the result of this query: SELECT SUBSTR(CITY_ID,2) FROM CITY;
Here,you will extract the string after E
,where E
always there in 1st position ,so we will find the string from the 2nd position
.
Then
SELECT TO_NUMBER(SUBSTR(CITY_ID,2)) FROM CITY ;
--this is converting the string into number.Then it will find the max number from the table CITY,and add 1 after that
SELECT MAX(TO_NUMBER(SUBSTR(CITY_ID,2)))+1 FROM CITY ;
And finally appending the constant E
with the result .
SELECT 'E'||(MAX(TO_NUMBER(SUBSTR(CITY_ID,2))+1)) INTO PKV
FROM CITY;
But take my suggestion ,create a sequence city_id_seq
,this will be better solution than what you are doing now.
CREATE SEQUENCE city_id_seq
MINVALUE 1
MAXVALUE 99999999999
START WITH 1
INCREMENT BY 1
CACHE 20;
CREATE OR REPLACE TRIGGER "HR"."PK_MAX_TRIGGER_CITY"
BEFORE INSERT ON CITY
FOR EACH ROW
DECLARE
v_city_id PLS_INTEGER;
BEGIN
SELECT city_id_seq.nextval INTO v_city_id FROM DUAL;
:NEW.CITY_ID :='E'||v_city_id ;
/* if you are using oracle 11g
:NEW.CITY_ID:='E'||city_id_seq.nextval;
*/
END;
/
Upvotes: 1
Reputation: 1155
The bracketed code ::
select LPAD(MAX(TO_NUMBER(SUBSTR('CT0015',3,LENGTH('CT0015')))+1),4,'0') from dual;
is actually cutting the value of city_id from 3 position to the end of the string then converting it to number data type adding 1 and then padding zeros to the left side
so in this case o/p 0016
Upvotes: 0