函数

时间:2017-11-26 10:46:51

标签: oracle

我创建了一个返回两个表之间匹配列的函数。该函数正确返回结果。

如何将函数的结果写为select statmenet中的列?

这是我的功能脚本:

CREATE OR REPLACE FUNCTION GML.GML_GET_COLUMNS (P_PREFIX VARCHAR2)
   RETURN VARCHAR2
IS
   V_COLUMNS   VARCHAR2 (1000);

   CURSOR CUR_COLUMNS
   IS
      SELECT   COLUMN_NAME
        FROM   USER_TAB_COLUMNS
       WHERE   TABLE_NAME = 'GML_SCENARIOS'
               AND COLUMN_NAME IN
                        (SELECT   COLUMN_NAME
                           FROM   GML_FILE_COLUMNS
                          WHERE   UPPER (ROW_PREFIX) NOT IN
                                        ('A', 'T', 'S', 'C', 'PH', 'AD')
                                  AND UPPER (ROW_PREFIX) = P_PREFIX);
BEGIN
   FOR I IN CUR_COLUMNS
   LOOP
      V_COLUMNS := V_COLUMNS || ',' || I.COLUMN_NAME;
   END LOOP;

   RETURN V_COLUMNS;
END;

例如:如果函数返回:'ID,First_name,Last_name',我怎么能像下面的语句一样使用结果:

select ID,first_name,Last_name from gml_scenarios 

2 个答案:

答案 0 :(得分:0)

我想你想要这样的代码:

SQL> CREATE OR REPLACE PROCEDURE GML_GET_COLUMNS(P_PREFIX VARCHAR2,P_TABLE_NAME VARCHAR2)
IS

   TYPE ScnCurTyp IS REF CURSOR;
   scn_cv   ScnCurTyp;
   scn_rec  gml_scenarios%ROWTYPE;
   sql_stmt VARCHAR2(32000);

   CURSOR CUR_COLUMNS
   IS
      SELECT   COLUMN_NAME
        FROM   USER_TAB_COLUMNS
       WHERE   TABLE_NAME = upper(p_table_name)
         AND   COLUMN_NAME IN
                        (SELECT   COLUMN_NAME
                           FROM   GML_FILE_COLUMNS
                          WHERE   UPPER (ROW_PREFIX) NOT IN
                                        ('A', 'T', 'S', 'C', 'PH', 'AD')
                                  AND UPPER (ROW_PREFIX) = P_PREFIX)
BEGIN
   FOR I IN CUR_COLUMNS
   LOOP
      DBMS_OUTPUT.PUT( lpad(I.COLUMN_NAME,20,' ') );
   END LOOP;


   sql_stmt := 'SELECT id, first_name, last_name FROM  '||v_table_name;
   OPEN scn_cv FOR sql_stmt;
   LOOP
     FETCH scn_cv INTO scn_rec;
     EXIT WHEN scn_cv%NOTFOUND;
     DBMS_OUTPUT.PUT_LINE(lpad(scn_rec.id,20,' ') || '  ' || lpad(scn_rec.first_name,20,' ')|| '  ' || lpad(scn_rec.last_name,20,' '));
   END LOOP;
   CLOSE scn_cv;

END;
SQL> set serveroutput on;
SQL> variable i_prefix varchar2;
SQL> variable i_table varchar2;
SQL> exec gml_get_columns(:i_prefix,:i_table);

答案 1 :(得分:0)

您可以使用此命令来实现目标:

select 'select ' || GML.GML_GET_COLUMNS('Your text') || ' from gml_scenarios ' from dual;