在一行中返回函数中的多个主键列。 PLSQL, SQL ORACLE 开发

RETURNING multiple Primary Key Columns in a Function on one line. PLSQL, SQL ORACLE DEV

我只是想找出如何在一个 DBMS 输出行中从 table 中 return 多个主键列....

在 table 我有以下...

The code for my function is:

    CREATE OR REPLACE FUNCTION Get_Constraint_Columns(
    /*
    * Oct 10th, 2021
    * Return the column names that make up a PK constraint and columns that make up unique constraint.
    */
    iTable VARCHAR2, iConstraint VARCHAR2
    )
    RETURN VARCHAR2
    AS
      wReturn VARCHAR2(30);
    CURSOR ColumnSelected IS
      SELECT Column_Name
      FROM User_Cons_Columns
      WHERE Table_Name = iTable AND Constraint_Name = iConstraint
      ORDER BY Position;
    CurrentRow User_Cons_Columns%ROWTYPE;
    
    BEGIN
     FOR CurrentRow IN ColumnSelected LOOP
    
       wReturn := (CurrentRow.Column_Name);
    
       RETURN wReturn; 
    
     END LOOP;
    
    END;
    /

当该函数被调用并且报告被 SPOOLED 时,我得到:

当我需要它看起来像:

它有两个列名...(MFR, PRODUCT) 我在代码中移动了一些东西并尝试了不同的东西,但它要么以相同的结果结束,要么以错误结束。如果有人能够指出我正确的方向,我将永远感激不已。提前致谢!

它失败的原因是 RETURN 语句立即退出了块。所以你只会得到循环的第一次迭代。将 RETURN 移出循环,AND 连接值以获得您想要得到的值:

create or replace FUNCTION get_constraint_columns(
    /*
    * Oct 10th, 2021
    * Return the column names that make up a PK constraint and columns that make up unique constraint.
    */
    itable VARCHAR2, iconstraint VARCHAR2
    )
    RETURN VARCHAR2
    AS
      wreturn VARCHAR2(30);
    CURSOR columnselected IS
      SELECT column_name
      FROM user_cons_columns
      WHERE table_name = itable AND constraint_name = iconstraint
      ORDER BY position;
    currentrow user_cons_columns%ROWTYPE;

    BEGIN
     FOR CurrentRow IN columnselected LOOP
       wreturn := wreturn ||', '||(currentrow.column_name);
       
     END LOOP;
     -- LTRIM removes the leading comma and space
     RETURN LTRIM(wreturn,', '); 
END;

使用LISTAGG可以简化这个函数。

create or replace FUNCTION get_constraint_columns(
    itable VARCHAR2, iconstraint VARCHAR2
)
RETURN VARCHAR2
AS
  wreturn VARCHAR2(4000); --4000 because 30 can be too small 
BEGIN
  SELECT LISTAGG(column_name, ', ') 
     WITHIN GROUP (ORDER BY position)
    INTO wreturn
    FROM user_cons_columns
   WHERE table_name = itable AND constraint_name = iconstraint
   ORDER BY position;
  RETURN wreturn;
END;