CREATE PROCEDURE add_name(name_param CHAR(20))
BEGIN
DECLARE dup_key CONDITION FOR SQLSTATE '02000';
DECLARE EXIT HANDLER FOR dup_key
BEGIN
INSERT INTO dup_names (name) VALUES (name_param);
SELECT 'duplicate key found, inserted into dup_names' AS result;
END
INSERT INTO unique_name (name) VALUES (name_param);
SELECT 'row inserted succesfully into unique_names' AS result;
END
注意事項;
定義store routine時用大寫或小寫都可以。
可以為某個condition宣告一個name,但並非必須。
CONDITION的宣告語法:http+www^slime/com*tw
DECLARE condition_name CONDITION FOR condition_type
HANDLER的宣告語法:http+www^slime/com*tw
DECLARE handler_type HANDLER FOR
condition_type [, condition_type] ...
statement
以下兩種指令的寫法意思是一樣的:http+www^slime/com*tw
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET exit_loop = 1;
或
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000'
BEGIN
SET exit_loop = 1;
END;
要與HANDLER產生連結的CONDITION必須為:
SQLSTATE value或MySQL error code
使用DECLARE CONDITION所宣告的condition_name
SQLWARNING:代表所有01開頭的SQLSTATE
NOT FOUND:代表所有02開頭的SQLSTATE
SQLEXCEPTION:所有除了SQLWARNING與NOT FOUND以外的值。
若要忽略某個CONDITION,只要指定給它一個空的CONTINUE HANDLER即可。
Cursorshttp+www^slime/com*tw
特性:
Read Only
循序讀取
DECLARE cursor_name CURSOR FOR select_statement
OPEN cursor_name
FETCH cursor_name INTO var_name [, var_name] ...
IF val IS NULL THEN
SELECT 'val is NULL';
ELSE
SELECT 'val is not NULL';
END IF;
======================
CASE val
WHEN 0 THEN SELECT 'val is 0';
WHEN 1 THEN SELECT 'val is 1';
ELSE SELECT 'val is not 0 or 1';
END CASE;
CASE val
WHEN val IS NULL THEN SELECT 'val is NULL'
WHEN val < 0 THEN SELECT 'val < 0';
WHEN val > 0 THEN SELECT 'val > 0';
ELSE SELECT 'val is 0';
END CASE;
SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME = 'routine_name'
AND ROUTINE_SCHEMA='db_name';
SHOW PROCEDURE STATUS LIKE 'w%';
SHOW FUNCTION STATUS;
SHOW CREATE PROCEDURE proc_name;
SHOW CREATE FUNCTION func_name;
Stored Routine Privileges and Execution Security
CREATE ROUTINE
EXECUTE
ALTER ROUTINE
GRANT OPTION
當你建立routine時,MySQL會自動付予你EXECUTE與ALTER ROUTINE權限。
EXECUTE、ALTER ROUTINE與GRANT OPTION權限可以針對個別的routine進行設定,但前提是該routine必須已經存在,例如:
GRANT EXECUTE, ALTER ROUTINE ON PROCEDURE world.world_record_count TO 'slime'@'localhost' WITH GRANT OPTION;
參考資料:www^slime^com^tw
Paul Dubois, Stefan Hinz, Carsten Pedersen(2005), “MySQL 5.0 Certification Study Guide.”