从Oracle存储过程返回输出参数

时间:2011-03-01 12:07:54

标签: sql oracle stored-procedures output-parameter

我正在尝试设置输出参数thirdPartyId的值,但我在missing or invalid option语句中收到错误set thirdPartyId

PROCEDURE usp_insert_user(  userType VARCHAR2,
                                logonId VARCHAR2,
                                title VARCHAR2,
                                firstName VARCHAR2,
                                middleName VARCHAR2,
                                lastName VARCHAR2,
                                comments VARCHAR2,
                                thirdPartyId OUT number) AS
      begin
        set thirdPartyId := select max(third_party_id) + 1 from third_party_user_temp;
        insert into THIRD_PARTY_USER_TEMP
            (Third_party_id,web_logon_id,prsn_type_cd,prsn_title_nm,
            prsn_first_nm,prsn_mdl_nm,prsn_last_nm,addtnl_third_party_txt)
            VALUES(thirdPartyId,logonId,upper(userType),title,
            firstName,middleName,lastName,comments)
        ;
    end usp_insert_user;

这样做的正确方法是什么?

谢谢!

更新:这样更安全吗?

insert into THIRD_PARTY_USER_TEMP
        (Third_party_id,web_logon_id,prsn_type_cd,prsn_title_nm,
        prsn_first_nm,prsn_mdl_nm,prsn_last_nm,addtnl_third_party_txt)
        VALUES((select max(third_party_id) + 1 from third_party_user_temp),logonId,upper(userType),title,
        firstName,middleName,lastName,comments)
        returning third_party_id into thirdPartyId

1 个答案:

答案 0 :(得分:3)

你可以这样做:

select max(third_party_id) + 1 into thirdPartyId from third_party_user_temp;

如果两个人可以同时运行此问题,则可能会遇到争用问题 - 两者都可能以相同的新thirdPartyId结束。您可以查看序列以避免这种情况。

<小时/> 如果你定义一个名为thirdPartyIdSeq的序列,你可以这样做:

PROCEDURE usp_insert_user(  userType VARCHAR2,
                                logonId VARCHAR2,
                                title VARCHAR2,
                                firstName VARCHAR2,
                                middleName VARCHAR2,
                                lastName VARCHAR2,
                                comments VARCHAR2,
                                thirdPartyId OUT number) AS
      begin
        insert into THIRD_PARTY_USER_TEMP
            (Third_party_id,web_logon_id,prsn_type_cd,prsn_title_nm,
            prsn_first_nm,prsn_mdl_nm,prsn_last_nm,addtnl_third_party_txt)
            VALUES(third_party_id_seq.nextval,logonId,upper(userType),title,
            firstName,middleName,lastName,comments)
        returning third_party_id into thirdPartyId;
    end usp_insert_user;

这使用序列生成下一个ID,returning子句填充OUT参数。

您也可以使用序列来避免该过程并在触发器中执行ID生成。这种方法有很多例子,尤其是在这个网站上。

CREATE OR REPLACE TRIGGER third_party_user_temp_bi
BEFORE INSERT ON third_party_user_temp
FOR EACH ROW
BEGIN
    SELECT thirdPartyIdSeq.NEXTVAL
    INTO   :new.third_party_id
    FROM   dual;
END;
/

您的插入不需要指定要使用的ID。