ORACLE)更新查询为什么不起作用?

时间:2019-08-29 01:32:27

标签: sql oracle

这是oracle pakage中的过程 更新查询 为什么不起作用?

create or replace PACKAGE BODY SAP_MATERIALMASTER_PKG IS

 PROCEDURE SAP_MATERIALMASTER_INS (
    TRANS_REF_NO   IN NUMBER,
    MATERIAL   IN VARCHAR2,
    UNIT_OF_MEASURE   IN CHAR )
      IS
      cnt NUMBER := 0;   
      BEGIN

        --insert or update 구분을 위한 동작
          select COUNT(*) into cnt from SAP_MATERIAL
          where
          material = MATERIAL;

        if cnt = 0 then 

          INSERT INTO SAP_MATERIAL(
          TRANS_REF_NO,MATERIAL,UNIT_OF_MEASURE
          ) 
          VALUES(TRANS_REF_NO,MATERIAL,UNIT_OF_MEASURE); commit;

        else

          UPDATE SAP_MATERIAL
          SET
          TRANS_REF_NO = TRANS_REF_NO, 
          MATERIAL = MATERIAL,
          UNIT_OF_MEASURE = UNIT_OF_MEASURE
          WHERE MATERIAL = MATERIAL;
          commit;
        end if;

      END SAP_MATERIALMASTER_INS;

 END  SAP_MATERIALMASTER_PKG;

2 个答案:

答案 0 :(得分:1)

修改参数!它们需要与列名不同。我建议使用前缀,在这种情况下为in_,以指示这些参数是“输入”参数:

PROCEDURE SAP_MATERIALMASTER_INS (
    in_TRANS_REF_NO   IN NUMBER,
    in_MATERIAL   IN VARCHAR2,
    in_UNIT_OF_MEASURE   IN CHAR
) as
cnt NUMBER := 0;   
BEGIN
    . . .
    UPDATE SAP_MATERIAL
         SET TRANS_REF_NO = in_TRANS_REF_NO, 
              UNIT_OF_MEASURE = in_UNIT_OF_MEASURE
          WHERE MATERIAL = in_MATERIAL;
     . . .

答案 1 :(得分:0)

关于@GordonLinoff的解决方案,我是否建议您学习使用MERGE语句?它旨在用更少的代码来精确地完成您正在做的事情:

PROCEDURE SAP_MATERIALMASTER_INS (pin_TRANS_REF_NO    IN NUMBER,
                                  pin_MATERIAL        IN VARCHAR2,
                                  pin_UNIT_OF_MEASURE IN CHAR )
  IS
  BEGIN
    MERGE INTO SAP_MATERIAL sm
      USING (SELECT pin_TRANS_REF_NO    AS P_TRANS_REF_NO,
                    pin_MATERIAL        AS P_MATERIAL,
                    pin_UNIT_OF_MEASURE AS P_UNIT_OF_MEASURE
               FROM DUAL) d
        ON (sm.MATERIAL = d.P_MATERIAL)
      WHEN NOT MATCHED THEN
        INSERT (TRANS_REF_NO,     MATERIAL,     UNIT_OF_MEASURE)
        VALUES (d.P_TRANS_REF_NO, d.P_MATERIAL, d.P_UNIT_OF_MEASURE)
      WHEN MATCHED THEN
        UPDATE
          SET sm.TRANS_REF_NO = d.P_TRANS_REF_NO,
              sm.UNIT_OF_MEASURE = d.P_UNIT_OF_MEASURE;

    COMMIT;
  END SAP_MATERIALMASTER_INS;

此外,SELECT COUNT(*)...可能非常慢。