get maxid from table and insert into another table using oracle procedure

时间:2016-05-11 11:31:45

标签: oracle

I'm trying to write a small oracle stored procedure. I want to get max of messageid from a table and store that value into another table.

I have written this....

create or replace procedure WITHOUT_TYPE is
vid int;
begin
TRUNCATE TABLE LOAD1;
select max(MESSAGEID) into vid from LOAD;
INSERT INTO LOAD1(vid) VALUES(vid);
end;
/

But not getting a value in vid in LOAD1 table.

Can anyone please check and help ?

1 个答案:

答案 0 :(得分:2)

You can rewrite it as follows:

CREATE OR REPLACE PROCEDURE WITHOUT_TYPE IS
  vOutput number;
BEGIN
    /* TRUNCATE is a DDL and can not be executed as a simple statement */
    DELETE LOAD1;

    /* you can directly insert your value, no need for a variable */
    INSERT INTO LOAD1(vid)
        SELECT MAX(MESSAGEID)
        FROM LOAD;

    /* retrieve the stored value */
    select vid
      into vOutput
    from LOAD1;
    dbms_output.put_line('Value: ' || vOutput);
END;
/

I removed the TRUNCATE because you can not use a DDL within a Pl/SQL procedure (without dynamic SQL); besides, TRUNCATE should only be used if strictly necessary, and very carefully.

Besides that, you don't need a variable to handle your max value; you can directly insert your value in the target table with a single insert-select statement;

相关问题