使用组合char创建触发器

时间:2012-12-07 09:30:18

标签: sql oracle triggers

我有这个工作代码。每次运行INSERT INTO "HR"."CITY" (CITY_ID) VALUES (0);时,CITY_ID中的数据都会增加一个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;

我想要做的是E1, E2 ... E15

我将代码更改为:

    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

首先将E1添加到数据库,但不是第二次。支架里面的东西只是让我难以消化。我希望这里的任何人能够向我解释支架中究竟发生了什么,并帮助我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您需要做的是修改您的Else零件查询。

SELECT 'E'||(MAX(TO_NUMBER(SUBSTR(CITY_ID,2))+1)) INTO PKV
    FROM CITY;

每当你想要找到括号中发生的事情时,请从内括号开始。

See the result of this query:  SELECT SUBSTR(CITY_ID,2) FROM CITY;

在这里,您将在E之后提取字符串,其中E始终位于第1个位置,因此我们将从2nd position中找到字符串。 然后

 SELECT TO_NUMBER(SUBSTR(CITY_ID,2)) FROM CITY ;

- 这是将字符串转换为数字。然后它会从表CITY中找到最大数字,然后再添加1

SELECT MAX(TO_NUMBER(SUBSTR(CITY_ID,2)))+1 FROM CITY ;

最后将常量E附加到结果。

SELECT 'E'||(MAX(TO_NUMBER(SUBSTR(CITY_ID,2))+1)) INTO PKV
    FROM CITY;

但是接受我的建议,创建一个序列city_id_seq,这将是比你现在所做的更好的解决方案。

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;
/

答案 1 :(得分:0)

括号内的代码::

select LPAD(MAX(TO_NUMBER(SUBSTR('CT0015',3,LENGTH('CT0015')))+1),4,'0') from dual;

实际上是将city_id的值从3位置切换到字符串的末尾,然后将其转换为数字数据类型,添加1,然后将零填充到左侧

所以在这种情况下o / p 0016