Select 使用 if oracle 从 cte 导入变量

Select into variables from cte using if oracle

我需要将 cte 中的值保存到过程中的变量中。 我的例子:

WITH test_cte AS (
SELECT *
from(
    SELECT date_a,lastName,firstName,birthDate, rank() over(ORDER BY date_a desc) rnk
    FROM test_table a
    join test_table b ON b.id = a.bid 
)a1
WHERE rnk =1)

SELECT count(*) into count_a 
FROM test_table a
join test_table b ON b.id = a.bid
WHERE a.code = code_name;



IF count_a > 0 THEN
    SELECT date_a,lastName,firstName,birthDate
    into date_a_var,lastName_var,firstName_var,birthDate_var
    FROM test_cte;
ELSE 
date_a_var := NULL;
lastName_var := NULL;
firstName_var := NULL;
birthDate_var := NULL;
END IF;

但是当我尝试编译它时出现下一个错误:

PL / SQL: ORA-00942: table or view does not exist

FROM test_cte;

我该怎么做才能解决这个问题?

在您的代码中:

-- Start of first SELECT statement.
WITH test_cte AS (
  SELECT *
  from(
    SELECT date_a,lastName,firstName,birthDate, rank() over(ORDER BY date_a desc) rnk
    FROM test_table a
    join test_table b ON b.id = a.bid 
  )a1
  WHERE rnk =1
)
SELECT count(*) into count_a 
FROM test_table a
join test_table b ON b.id = a.bid
WHERE a.code = code_name;
-- End of first SELECT statement.

IF count_a > 0 THEN
  -- Start of second SELECT statement.
  SELECT date_a,lastName,firstName,birthDate
  into date_a_var,lastName_var,firstName_var,birthDate_var
  FROM test_cte;
  -- End of second SELECT statement.
ELSE 
  date_a_var := NULL;
  lastName_var := NULL;
  firstName_var := NULL;
  birthDate_var := NULL;
END IF;

它不会工作,因为 test_cte 仅存在于一个语句中,当您完成该语句的最后一个 SELECT 语句时,它不再存在于后续语句中。 (但是,您没有在 SELECT 中为该语句使用子查询分解子句 [a.k.a.CTE],因此不清楚为什么需要 WITH 子句。)

与其尝试使用 COUNT,不如获取数据并在发生 NO_DATA_FOUND 异常时进行处理(另外,从 Oracle 12 开始,您不需要使用 RANK 并且可以改用 FETCH FIRST ROW WITH TIES):

DECLARE
  date_a_var    test_table.date_a%TYPE;
  lastName_var  test_table.lastname%TYPE;
  firstName_var test_table.firstname%TYPE;
  birthDate_var test_table.birthdate%TYPE;
BEGIN
  BEGIN
    SELECT date_a,
           lastName,
           firstName,
           birthDate
    INTO   date_a_var,
           lastName_var,
           firstName_var,
           birthDate_var
    FROM   test_table a
           join test_table b ON b.id = a.bid 
    ORDER BY date_a DESC
    FETCH FIRST ROW WITH TIES;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      date_a_var    := NULL;
      lastName_var  := NULL;
      firstName_var := NULL;
      birthDate_var := NULL;
  END;

  -- Continue processing
END;

(注意:如果有重复日期,您也可能会得到 TOO_MANY_ROWS 异常。要么使用 FETCH FIRST ROW ONLY,要么在 Oracle 12 之前,使用 ROW_NUMBER 分析函数。)