批量收集到一个SQL块中

时间:2019-04-10 07:55:56

标签: sql oracle plsql

我的PL / SQL存储过程中有一个SQL块。该块使用批量收集将值收集到用户定义的类型中。

TYPE risks IS TABLE OF NUMBER;
o_risks risks;

... 

SELECT DISTINCT risk
BULK   COLLECT
INTO   o_risks
FROM   schema.risks
WHERE parent_id = any_id

但是我也想将这个SQL块中的max(other_column_name)保存到数字变量中。使用批量收集时可以吗?当然,我可以创建另一个块,但是看起来不正确。

1 个答案:

答案 0 :(得分:3)

使用CASTCOLLECT

Oracle设置

CREATE TYPE risks IS TABLE OF NUMBER;
/

CREATE TABLE risk_table ( risk, other_column_name, parent_id ) AS
SELECT 1, 1, 1 FROM DUAL UNION ALL
SELECT 3, 2, 1 FROM DUAL UNION ALL
SELECT 1, 4, 1 FROM DUAL UNION ALL
SELECT 2, 2, 1 FROM DUAL UNION ALL
SELECT 3, 1, 1 FROM DUAL UNION ALL
SELECT 3, 2, 1 FROM DUAL UNION ALL
SELECT 4, 5, 2 FROM DUAL;

PL / SQL

DECLARE
  o_risks             risks;
  o_other_column_name RISK_TABLE.OTHER_COLUMN_NAME%TYPE;
  any_id              RISK_TABLE.PARENT_ID%TYPE := 1;
BEGIN
  SELECT CAST( COLLECT( DISTINCT risk ) AS risks ),
         MAX( other_column_name )
  INTO   o_risks, o_other_column_name
  FROM   risk_table
  WHERE  parent_id = any_id;

  DBMS_OUTPUT.PUT_LINE( 'Max other column name: ' || o_other_column_name );
  FOR i IN 1 .. o_risks.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE( 'Risk ' || i || ': ' || o_risks(i) );
  END LOOP;
END;
/

输出

Max other column name: 4
Risk 1: 1
Risk 2: 2
Risk 3: 3

db <>提琴here

如果您使用的COLLECT( DISTINCT ... )版本不起作用,则可以使用SET( CAST( COLLECT( risk ) AS risks ) )来获得不同的值。