将变量分配给PL / SQL块内的子查询结果

时间:2016-11-02 19:29:11

标签: oracle plsql

这是一个更简化的伪代码,描述了我想要做的事情:

DECLARE
  CURSOR CURSOR_A IS
    SELECT FIELD_A1, FIELD_A2
    FROM TABLE_A;
vNAME NVARCHAR2(100) := NULL;
BEGIN
FOR RECORD_A IN CURSOR_A LOOP
  IF (RECORD_A.FIELD_A1 IS NOT NULL) THEN
    vNAME := RECORD_A.FIELD_A1;
  ELSE
    vNAME := (SELECT FIELD_B
                FROM TABLE_B
               WHERE TABLE_B.B2 = RECORD_A.A2)
END LOOP;
END;
/

我不允许在PL / SQL块中包含SELECT语句吗?

3 个答案:

答案 0 :(得分:4)

所有你需要的 - 一个选择。试试吧:

declare
    name nvarchar2(100) := null;
begin
    for row_ in (
        select field_a1, field_b from table_a left outer join table_b on b2 = a2
    ) loop
        name := coalesce(row_.field_a1, row_.field_b);
        -- do something
    end loop;
end;
/

如果两个表中的行太多并且关注性能,您仍然可以将... and field_a1 is null添加到on-clause。

答案 1 :(得分:2)

您可以选择,但需要指定存储所选数据的变量

DECLARE
  CURSOR CURSOR_A IS
    SELECT FIELD_A1, FIELD_A2
    FROM TABLE_A;
vNAME NVARCHAR2(100) := NULL;
BEGIN
FOR RECORD_A IN CURSOR_A LOOP
  IF (RECORD_A.FIELD_A1 IS NOT NULL) THEN
    vNAME := RECORD_A.FIELD_A1;
  ELSE
        SELECT FIELD_B into vNAME 
                FROM TABLE_B
               WHERE TABLE_B.B2 = RECORD_A.A2;
END LOOP;
END;
/

答案 2 :(得分:0)

我们需要在子句中将select语句的值存储在Begin和end块中。 请查看以下示例突出显示的行:

DECLARE
  CURSOR CURSOR_A IS
    SELECT FIELD_A1, FIELD_A2
    FROM TABLE_A;
vNAME NVARCHAR2(100) := NULL;
BEGIN
FOR RECORD_A IN CURSOR_A LOOP
  IF (RECORD_A.FIELD_A1 IS NOT NULL) THEN
    vNAME := RECORD_A.FIELD_A1;
  ELSE
    SELECT FIELD_B into vNAME --**highlighted line**
                FROM TABLE_B
               WHERE TABLE_B.B2 = RECORD_A.A2
END LOOP;
END;