2016-07-04 69 views
0

我是oracle的新手,我正面臨着創建存儲過程的這個問題。如果有人能幫忙,我會很感激。在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` 

回答

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; 
+0

受影響的行,謝謝你的解決方案 – qwerty

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;