示例:创建简单的存储过程。

    • 准备相关表
    1. create table t1(id number not null primary key, name varchar2(50) not null, gmt_create date not null default sysdate, unique (name));
    2. create sequence seq_t1 start with 10000 increment by 1 cache 50 nocycle;
    • 创建存储过程
    1. delimiter /
    2. CREATE OR REPLACE PROCEDURE sp_insert_t1( p_name varchar2 )
    3. AS
    4. BEGIN
    5. INSERT INTO t1(id, name) values(seq_t1.nextval, p_name) ;
    6. COMMIT;
    7. dbms_output.put_line('Add a row which name is : ' || p_name );
    8. EXCEPTION
    9. WHEN OTHERS THEN
    10. ROLLBACK;
    11. dbms_output.put_line('Exception raised!');
    12. END ;
    13. /
    14. delimiter ;
    • 执行存储过程
    1. obclient> set serveroutput on ;
    2. Query OK, 0 rows affected (0.22 sec)
    3. obclient> select * from t1;
    4. Empty set (0.01 sec)
    5. obclient> call sp_insert_t1('A');
    6. Query OK, 0 rows affected (0.05 sec)
    7. Add a row which name is : A
    8. obclient> select * from t1;
    9. +-------+------+---------------------+
    10. | ID | NAME | GMT_CREATE |
    11. +-------+------+---------------------+
    12. | 10000 | A | 2020-04-02 18:37:24 |
    13. +-------+------+---------------------+
    14. 1 row in set (0.00 sec)
    15. obclient> call sp_insert_t1('B');
    16. Query OK, 0 rows affected (0.00 sec)
    17. Add a row which name is : B
    18. obclient> call sp_insert_t1('A');
    19. Query OK, 0 rows affected (0.01 sec)
    20. Exception raised!
    21. obclient> select * from t1;
    22. +-------+------+---------------------+
    23. | ID | NAME | GMT_CREATE |
    24. +-------+------+---------------------+
    25. | 10000 | A | 2020-04-02 18:37:24 |
    26. | 10001 | B | 2020-04-02 18:37:41 |
    27. +-------+------+---------------------+
    28. 2 rows in set (0.00 sec)