Oracle - 在SELECT语句中使用变量

时间:2015-02-21 17:36:33

标签: oracle plsql oracle11g

我在SQL中的背景是SQL Server,所以原谅我以类似的方式使用Oracle。我需要使用变量,以便我可以使用其中存储的值来执行单独的SELECT查询。我的目标是找到一个百分比值,变量将保存一个表的总值。

DECLARE
  v_Count INT;

BEGIN

--get total rows
SELECT COUNT(OrderID)
INTO v_Count
FROM OrderedEquipment;

--find percentage of equipment ordered
SELECT a.Equip_Name, COUNT(b.EquipmentID), ((COUNT(b.EquipmentID)*1.0)/(v_Count*1.0)*100)
FROM Equipment a
LEFT OUTER JOIN OrderedEquipment b ON a.EquipmentID = b.EquipmentID
GROUP BY a.Equip_Name;

END;

SQL Developer将抛出此错误:

Error report -
ORA-06550: line 10, column 1:
PLS-00428: an INTO clause is expected in this SELECT statement

我尝试寻找解决方案,并偶然发现了这篇文章:

How do I use variables in Oracle SQL Developer?

但没有一个答案能真正解决我的问题。我尝试使用bind变量示例,但这不起作用。

1 个答案:

答案 0 :(得分:1)

最简单的方法是不使用变量

SELECT a.Equip_Name, COUNT(b.EquipmentID), 
    (COUNT(b.EquipmentID)*1.0)/((SELECT COUNT(OrderID) cnt FROM OrderedEquipment)*1.0)*100
  FROM Equipment a
  LEFT OUTER JOIN OrderedEquipment b ON a.EquipmentID = b.EquipmentID
  GROUP BY a.Equip_Name;

您也可以在您的区块中选择数据为3个变量

... a.Equip_Name into v1, COUNT(b.EquipmentID) into v2,
  ((COUNT(b.EquipmentID)*1.0)/(v_Count*1.0)*100) into v3 ...

并列出

dbms_output.put_line(v1||' '||v2||' '||v3);

编辑 - 此查询应该更快:

with counter as (select count(OrderID) cnt from OrderedEquipment)
select a.Equip_Name, count(b.EquipmentID), 
    (count(b.EquipmentID)*1.0)/(max(counter.cnt)*1.0)*100
  from Equipment a
    left join OrderedEquipment b ON a.EquipmentID = b.EquipmentID
    cross join counter
  group by a.Equip_Name;