【问题标题】:PL/SQL Joining tables inside of an iterationPL/SQL 在迭代内连接表
【发布时间】:2014-04-08 09:30:16
【问题描述】:

上周我只是在尝试自学 PL/SQL 过程,并且遇到了一些初学者问题,了解循环/游标如何与连接结合使用。

任何人可以阐明的任何观点都会很棒,因为我对游标周围的一些 PL/SQL 概念很陌生。

提前为这个高度晦涩的例子道歉

在下面的示例中,我基本上从表 A 开始并尝试获取客户的名称,然后通过以下方式设置一个 reason_code 标志:a) 检查表 B 上的连接是否成功,如果连接失败则检查客户是否位于区域 B(使用表 C)。在下面的假设示例中,我还尝试创建一个包含来自另一个表(客户名称)的数据的输出。

我尝试使用与以下类似的方法进行连接:

声明

order_cnt 整数;

光标base1是 选择 customer_id、订阅、原因码 来自客户订阅

开始

base1 循环中的 base_rec

选择计数(*)

进入 order_cnt

来自客户订阅基地,客户订单

其中 base.customer_id = order.customer_id;

如果 order_cnt > 1 那么

update customerssubscription set reasoncode = '已订购产品'

base_rec 的当前位置;

否则...

结束循环

结束;

如您所见,我试图为基表打开一个游标并遍历每条记录,加入其他表以设置标志。这不起作用,我认为它是我尝试加入的方式,因为它没有指定当前行。我也没有找到任何加入数据检索的例子,我试图推导客户名称

表 A:客户订阅

Customer_ID | SubscriptionID | reasoncode
123         | 567            |
124         |                |

表 B:客户订单

Customer_ID | Order_ID | Product
123         | 567      | TITANIC

表 C:客户

Customer_ID | Name    | Area     
123         | Roger   | E     
124         | Timothy | B     

输出:表 A

Customer_ID | Name    | ReasonCode     
123         | Roger   | Has ordered Product    
124         | Timothy | Outside of area     

【问题讨论】:

    标签: loops join plsql iteration


    【解决方案1】:

    试试这个,

    Select c.Customer_ID 
        ,c.Name
        ,Case When co.Order_id is not null 
                Then 'Has ordered Product'
              When Area ='B'
                Then 'Outside of area'
              Else 'UnKnown'
         End as ReasonCode
     from Customer as c
    left join CustomerOrder as co on c.Customer_ID =co.Customer_ID 
    

    如果每个客户的 CustomerOrder 表中有多个条目,则需要更改查询,如下所示,

    Select c.Customer_ID 
        ,c.Name
        ,Case When exists(Select COUNT(co.Order_ID) from CustomerOrder as co where c.Customer_ID =co.Customer_ID) 
             Then 'Has ordered Product'
              When Area ='B'
                Then 'Outside of area'
              Else 'UnKnown'
         End as ReasonCode
     from Customer as c
    

    【讨论】:

    • 感谢您的帮助,但我实际上特别希望使用迭代来解决此问题并使用结果更新表
    • @user3484575,如果迭代,然后尝试使用 while 循环。
    • 谢谢您,您能否提供一个示例,说明如何实际连接循环中的每条记录?我从根本上难以理解如何在语法上使每条记录连接到另一个表以检索/检查值的存在。感谢您对此有所了解
    • 当然,给我一些时间
    • 在上面的例子中它是 reason_code,但我真的只是为了说明的目的把那个例子放在那里。我真的只是想学习有关显式游标和迭代的概念。非常感谢,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2010-11-02
    • 2021-07-31
    相关资源
    最近更新 更多