1

这是我的 MYSQL 代码。在这里,我想将其转换为 PL/SQL

Select 
products.productID,
products.productName,
orderDetails.quantity,
orderDetails.unitPrice,
orderDetails.unitPrice*orderDetails.quantity as sub_total,
orderDetails.discount as taxes 
from products 
inner join Orderdetails on products.productID=orderDetails.productID

如何将其转换为 PL/SQL?

4

1 回答 1

2

PL/SQL 的意思是“Oracle”,因为它是 SQL 的过程扩展。换句话说,我们在 SQL 中编写“查询”,我们在 PL/SQL 中编写过程、函数、包、触发器和东西。

如果您只是感到困惑并且 - 实际上 - 想要在 Oracle 的 SQL 中运行该查询,那么您不必做任何事情,因为它可以正常工作(假设具有这些列的表存在于您连接到的模式中)。不过,我建议您使用表别名,因为它们使代码更易于阅读,例如

select 
  p.productid,
  p.productname,
  o.quantity,
  o.unitprice,
  o.unitprice * o.quantity as sub_total,
  o.discount as taxes 
from products p inner join orderdetails o on p.productid = o.productid;

如果您真的想切换到 PL/SQL,那么匿名 PL/SQL 块就可以了(即您不需要过程或函数;您真正需要的取决于您接下来要做什么)。在 PL/SQL 中,你必须选择INTO一些东西;例如,本地声明的变量。但是,由于您的查询不包含where子句,它将返回productid值在两个表中匹配的所有行,并且可以是无行、一行或多行。对于没有行,您必须处理no_data_found异常。对于一排,它会起作用。对于许多行,您必须处理too_many_rows异常。因此,使用光标循环可能是个好主意FOR——这就是我将要演示的内容——并简单地在屏幕上显示找到的内容(我将只显示两个值,

set serveroutput on
begin
  for cur_r in (select 
                  p.productid,
                  p.productname,
                  o.quantity,
                  o.unitprice,
                  o.unitprice * o.quantity as sub_total,
                  o.discount as taxes 
                from products p inner join orderdetails o on p.productid = o.productid
               )
  loop
    dbms_output.put_line(cur_r.productname ||', '|| cur_r.sub_total);
  end loop;
end;
/

正如我所说:该代码的真正外观取决于您想用它做什么。

于 2021-10-24T13:34:30.730 回答