循环索引的“无效标识符”错误消息(在Oracle SQL Developer中)

时间:2013-10-25 14:13:26

标签: for-loop oracle-sqldeveloper

为什么运行以下行时,循环变量索引(i)出现“invalid identifer”错误消息?

SQL错误:ORA-00904:“我”:标识符无效

for i in 1..5 loop
   select Price from Orders where (ID=i);
end loop;

Orders是一个包含两个字段的表:ID和Price。

表格订单:

ID   Price
------------
1     1200    
2     2250    
3     1750    
4     2000    
5     1000    
6     300    

2 个答案:

答案 0 :(得分:1)

您可能需要将其作为匿名块运行?这是一个如何使循环工作的简单示例:

DECLARE
  v_last_name VARCHAR2(2000);

BEGIN
  for i in 1..5 loop

    WITH sample_set AS (
      SELECT 1 the_number, 'frank' last_name FROM DUAL UNION ALL
      SELECT 2 the_number, 'STEVE' last_name FROM DUAL UNION ALL
      SELECT 3 the_number, 'CARL' last_name FROM DUAL UNION ALL
      SELECT 4 the_number, 'bella' last_name FROM DUAL UNION ALL
      SELECT 5 the_number, 'tank' last_name FROM DUAL)
    select last_name
    INTO   v_last_name
    from sample_set where the_number = i;

    dbms_output.put_line(v_last_name);

  end loop;
END;

答案 1 :(得分:0)

这样做

DECLARE 
my_price long;
BEGIN
FOR I IN 1..5 loop
SELECT PRICE INTO MY_PRICE FROM ORDERS where id=i;
DBMS_OUTPUT.PUT_LINE('The price is'||' '||my_price);
end loop;
end;

OUTPUT
-------------------------------
The price is 1234
The price is 1235
The price is 1236
The price is 1237
The price is 1238

Statement processed.