0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

oracle procedure

Last updated at Posted at 2020-05-21

oracle procedure (無名ブロック) についていろいろ(文句)を書く!

1.構造のみだけはダメ!

DECLARE /*宣言セクション */

BEGIN /*実行可能セクション */

EXCEPTION /*例外セクション */

END;
/

これ、エラーになる。以下の最小限ソース、それぞれのセクションの中、なんかしらの処理が必要。

DECLARE /*宣言セクション */
    ddate date;
BEGIN  /*実行可能セクション */
    select sysdate into ddate from dual;
EXCEPTION  /*例外セクション */
    when others then
    dbms_output.put_line('エラー発生!!');
END;
/

if 文もそう

IF (condition) THEN

END IF;

だと、エラーになる。

IF (condition) THEN
    dbms_output.put_line('TARGET!');
END IF;

は大丈夫。

2.デフォルトはログ出力しない。

dbms_output.put_line('エラー発生!!');

出力は何もしない。
毎回 google が、https://www.projectgroup.info/tips/Oracle/Oracle_000012.html に解決方法がある。

SET SERVEROUTPUT ON;

をやらないとダメ。。。。。

DBMS_OUTPUT.ENABLE (buffer_size => NULL);

をやらないとダメ。。。。。の説もある。

3.動的SQL(結構面倒)
参考になるページ
https://sql-oracle.com/?p=1468
https://docs.oracle.com/cd/E16338_01/appdev.112/b56260/dynamic.htm

4.エラーメッセージは糞。

付録(参考になったサイト)
PL/SQL カーソルの実行方法メモ
PL/SQL で直前に実行したSQLの結果行数を取得する方法

付録2(比較的にいい例→何でもあり)
関数、動的SQLバインド変数更新、例外処理、カーソルクローズ、SQLエラー出力

--SET SERVEROUTPUT ON;

DECLARE 	/*宣言セクション */
	ddate date; -- テスト用、削除可

	PROCEDURE FUNC3(param VARCHAR2) IS
		RESULT_COUNT number;
		TYPE cur_typ IS REF CURSOR;  -- カーソル
		emp_cur cur_typ;
	BEGIN
		DBMS_OUTPUT.PUT_LINE('処理:'||param);

		EXECUTE IMMEDIATE 'update table1 set flag = ''1'' where XX_CODE = :XX_CODE' USING param;
		RESULT_COUNT := SQL%ROWCOUNT;
		dbms_output.put_line('RESULT_COUNT='||RESULT_COUNT);
	EXCEPTION
		when others then
	        -- 例外が起きた時も必ずcloseする
	        IF emp_cur%ISOPEN THEN
	            CLOSE emp_cur;
	        END IF;
			DBMS_OUTPUT.PUT_LINE(sqlcode);
			DBMS_OUTPUT.PUT_LINE(sqlerrm);
			RAISE;
	END FUNC3;

BEGIN   /*実行可能セクション */
	DBMS_OUTPUT.ENABLE (buffer_size => NULL);

	select sysdate into ddate from dual;
	dbms_output.put_line(ddate);

	FUNC3('aa');
	FUNC3('BB');

	COMMIT;

EXCEPTION    /*例外セクション */
	when others then
		ROLLBACK;
		RAISE;
END;

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?