Oracle 存储过程中的 UNION

Posted

技术标签:

【中文标题】Oracle 存储过程中的 UNION【英文标题】:UNION in Oracle Stored Procedure 【发布时间】:2014-03-12 21:05:21 【问题描述】:

我正在尝试在 Oracle 中做最基本的存储过程。我只是想返回由联合加入的 2 个查询...代码如下:

CREATE OR REPLACE PROCEDURE GETATMCONTRACTSBYMANAGERID  (
   MANAGERID IN NUMBER
) AS 
BEGIN
  select t.ID, t."NUMBER", t.TITLE, t.NOTES, t.CONTRACT_TYPE_ID as CONTRACT_TYPE_ID,   t.CONTRACT_STATUS_ID as CONTRACT_STATUS_ID, t.TASK_NUMBER as TASK_NUMBER, c.CONSULTANT_ID,t.TASK_MANAGER_ID, t.IS_COMPREHENSIVE, t."NUMBER", TO_DATE(SUBSTR(t."NUMBER", 8, 2), 'rr')  as val, SUBSTR(t."NUMBER", 11, 3) as val2, t.REF_ID from CONTRACT t INNER JOIN CONTRACT c on c.ID = t.REF_ID
  where t.TASK_MANAGER_ID = MANAGERID;
  UNION 
  select t.ID, t."NUMBER", t.TITLE, t.NOTES, t.CONTRACT_TYPE_ID as CONTRACT_TYPE_ID, t.CONTRACT_STATUS_ID as CONTRACT_STATUS_ID, t.TASK_NUMBER as TASK_NUMBER, t.CONSULTANT_ID, t.TASK_MANAGER_ID, t.IS_COMPREHENSIVE, t."NUMBER", TO_DATE(SUBSTR(t."NUMBER", 8, 2), 'rr')  as val, SUBSTR(t."NUMBER", 11, 3) as val2, t.REF_ID from CONTRACT t
  where t."NUMBER" in (select "NUMBER" from Contract t1 where t1.TASK_MANAGER_ID = MANAGERID)
    and t.TASK_NUMBER = ' '
  order by val desc, val2 desc, TASK_NUMBER asc;
END GETATMCONTRACTSBYMANAGERID;

我将是第一个承认我对 SQL Server 比对 oracle 更舒服的人,但对我来说它似乎应该可以工作。

它返回的错误是:

错误(7,1):PLS-00103:在预期以下情况之一时遇到符号“UNION”:(begin case declare end exception exit for goto if loop mod null pragma raise return select update while with

对于这个问题的任何帮助将不胜感激:)

【问题讨论】:

您当前的问题是UNION 之前的分号。但是,一旦您解决了这个问题,您就会遇到另一个问题,因为您不使用查询的结果。你想做什么? 【参考方案1】:

union 运算符之前有一个多余的分号 (;) - 只需将其删除即可:

select t.ID, t."NUMBER", t.TITLE, t.NOTES, t.CONTRACT_TYPE_ID as CONTRACT_TYPE_ID,   t.CONTRACT_STATUS_ID as CONTRACT_STATUS_ID, t.TASK_NUMBER as TASK_NUMBER, c.CONSULTANT_ID,t.TASK_MANAGER_ID, t.IS_COMPREHENSIVE, t."NUMBER", TO_DATE(SUBSTR(t."NUMBER", 8, 2), 'rr')  as val, SUBSTR(t."NUMBER", 11, 3) as val2, t.REF_ID from CONTRACT t INNER JOIN CONTRACT c on c.ID = t.REF_ID
  where t.TASK_MANAGER_ID = MANAGERID -- Semicolon removed here
  UNION 
  select t.ID, t."NUMBER", t.TITLE, t.NOTES, t.CONTRACT_TYPE_ID as CONTRACT_TYPE_ID, t.CONTRACT_STATUS_ID as CONTRACT_STATUS_ID, t.TASK_NUMBER as TASK_NUMBER, t.CONSULTANT_ID, t.TASK_MANAGER_ID, t.IS_COMPREHENSIVE, t."NUMBER", TO_DATE(SUBSTR(t."NUMBER", 8, 2), 'rr')  as val, SUBSTR(t."NUMBER", 11, 3) as val2, t.REF_ID from CONTRACT t
  where t."NUMBER" in (select "NUMBER" from Contract t1 where t1.TASK_MANAGER_ID = MANAGERID)
    and t.TASK_NUMBER = ' '
  order by val desc, val2 desc, TASK_NUMBER asc;

【讨论】:

【参考方案2】:

除了分号问题,您还需要选择 INTO 变量来编译您的代码。

【讨论】:

以上是关于Oracle 存储过程中的 UNION的主要内容,如果未能解决你的问题,请参考以下文章

oracle中的存储过程怎么写

oracle中的存储过程,有啥作用,以及怎么在代码中使用?

oracle中的存储过程如何返回查询到的多个值?

带有 union all 的存储过程循环

关于oracle存储过程中的sql拼接,大神进!!!

如何调用ORACLE程序包中的存储过程