示例:创建独立的函数。
delimiter /
CREATE OR REPLACE FUNCTION f_maxid_of_t1 RETURN number
IS
i_id number := -1;
BEGIN
SELECT max(id) INTO i_id FROM t1 ;
RETURN i_id;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END;
/
delimiter ;
执行函数。
obclient> select * from t1;
+-------+------+---------------------+
| ID | NAME | GMT_CREATE |
+-------+------+---------------------+
| 10000 | A | 2020-04-02 18:37:24 |
| 10001 | B | 2020-04-02 18:37:41 |
| 10003 | C | 2020-04-02 18:45:07 |
| 10004 | D | 2020-04-02 18:45:08 |
| 10005 | E | 2020-04-02 18:45:10 |
+-------+------+---------------------+
5 rows in set (0.00 sec)
obclient> select f_maxid_of_t1() from dual;
+-----------------+
| F_MAXID_OF_T1() |
+-----------------+
| 10005 |
+-----------------+
1 row in set (0.03 sec)
obclient> truncate table t1;
Query OK, 0 rows affected (0.11 sec)
obclient> select f_maxid_of_t1() from dual;
+-----------------+
| F_MAXID_OF_T1() |
+-----------------+
| NULL |
+-----------------+
1 row in set (0.02 sec)