在oracle中编写存储过程

时间:2016-07-04 09:31:25

标签: oracle stored-procedures

我是oracle的新手,我遇到了创建存储过程的问题。如果有人能提供帮助,我将非常感激。

Create procedure in `ABC` schema with input params as: `NUM1`, `STATUS1`

Check if `NUM` exists in `ABC.STATUS` table

If exists

Update the `STATUS` with input parameter passed and `LAST_UPDATED` with `SYSDATE` of `ABC.STATUS`

Else

Insert record with `NUM` and `STATUS` with input parameters and `LAST_UPDATED` with `SYSDATE` of `ABC.STATUS`

2 个答案:

答案 0 :(得分:1)

以下是该程序的一个示例:

CREATE OR REPLACE PROCEDURE abc.myproc(num1 AS NUMBER, status1 AS NUMBER) IS

    lc_count NUMBER;

BEGIN

    SELECT COUNT(*) INTO lc_count
    FROM abc.status
    WHERE num = num1;

    IF lc_count > 0 THEN
        -- Update status of existing record
        UPDATE abc.status
        SET status = status1,
            last_updated = SYSDATE
        WHERE num = num1;
    ELSE
        -- Create new record
        INSERT INTO abc.status(
            num, 
            status, 
            last_updated
        ) VALUES (
            num1, 
            status1, 
            SYSDATE
        );
    END IF;

    COMMIT; -- Commit transaction;

EXCEPTION
    WHEN OTHERS THEN
        ROLLBACK -- Rollback transaction;
        RAISE;   -- Throws again the exception
END;

答案 1 :(得分:0)

您可以使用SQL%ROWCOUNT来检测受影响的行,例如

create or replace procedure proc(p_num number, p_status number) is
begin

  UPDATE abc.status
     SET status = p_status,
         last_updated = sysdate
   WHERE num = p_num;

  -- if update is not executed, then insert
  if SQL%ROWCOUNT = 0 then

    INSERT INTO status(
              num, 
              status, 
              last_updated
          ) VALUES (
              p_num, 
              p_status, 
              sysdate
          );
  end if;

end proc;