如何将MYSQL转换为PL/SQL



这是我的MYSQL代码。这里我想将This转换为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?

PL/SQL的意思是"oracle",因为它是对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;
/

就像我说的:代码看起来是什么样子取决于你想用它做什么。

最新更新