在功能和异步呼叫问题中打开和关闭游标

时间:2016-07-21 08:33:02

标签: sql postgresql plpgsql

我已经用2种方式编写了postgresql函数。实际上我已经从Oracle转换了它。它工作正常。但是我在最后一部分写了一些混淆。请检查功能并给我建议。谢谢你的耐心等待。

Postgresql版本:9.2

选项#1:

-- Function: to_tdfkcd(character varying)

-- DROP FUNCTION to_tdfkcd(character varying);

CREATE OR REPLACE FUNCTION to_tdfkcd(i_tdfkname character varying)
  RETURNS character varying AS
$BODY$
DECLARE
    CUR_TDFK CURSOR (V_TDFKNAME character varying) FOR SELECT TDFKCD FROM TM_TDFK WHERE TDFKNAME = TRIM(V_TDFKNAME);
    V_RETURN TM_TDFK.TDFKCD%TYPE;
BEGIN
    V_RETURN := NULL;
    FOR CUR_TDFK_DT IN CUR_TDFK (I_TDFKNAME ) LOOP
        IF CUR_TDFK_DT.TDFKCD IS NULL OR CUR_TDFK_DT.TDFKCD = ''
        THEN
            RETURN V_RETURN;
        ELSE
            RETURN CUR_TDFK_DT.TDFKCD;
        END IF;
    END LOOP;  
END;
$BODY$
  LANGUAGE plpgsql VOLATILE

检查选项#1的功能结果:

SELECT TO_TDFKCD('国外');

Output:

99

选项#2:

-- Function: to_tdfkcd(character varying)

-- DROP FUNCTION to_tdfkcd(character varying);

CREATE OR REPLACE FUNCTION to_tdfkcd(i_tdfkname character varying)
  RETURNS character varying AS
$BODY$
DECLARE 
 V_RETURN character varying DEFAULT '';
 CUR_TDFK_DT RECORD;
 CUR_TDFK CURSOR (V_TDFKNAME character varying)
 FOR SELECT TDFKCD 
 FROM TM_TDFK
 WHERE TDFKNAME = TRIM(V_TDFKNAME);
BEGIN
   -- Open the cursor
   OPEN CUR_TDFK(I_TDFKNAME);

   LOOP
    -- fetch row into the table
      FETCH CUR_TDFK INTO CUR_TDFK_DT;
    -- exit when no more row to fetch
      EXIT WHEN NOT FOUND;

    -- build the output
      IF CUR_TDFK_DT.TDFKCD IS NULL OR CUR_TDFK_DT.TDFKCD = ''
      THEN
        V_RETURN := NULL;
      ELSE
        V_RETURN := CUR_TDFK_DT.TDFKCD;
      END IF;
   END LOOP;

   -- Close the cursor
   CLOSE CUR_TDFK;

   RETURN V_RETURN;
END; $BODY$
  LANGUAGE plpgsql VOLATILE

检查选项#2的功能结果:

SELECT TO_TDFKCD('国外');

Output:

99

我有一些疑问。

  1. 我更喜欢哪一个? Option#1Option#2
  2. 有没有复杂性?
  3. Option#2 OPEN CLOSE 光标可以解决任何问题 多线程环境还是从我的Web应用程序同时调用?

0 个答案:

没有答案