Oracle PL/SQL: for i in (select) statement

Discussion in 'Databases' started by ceemage, Aug 28, 2012.

  1. #1
    I am fairly confident with "normal" SQL, but start to get rather more wobbly whenever I go near PL/SQL.

    I have a table, called (imaginatively) data_table:

    +------------------------------+
    | prim_key | field1  | field 2 |
    +------------------------------+
    | 001      | Hello   | World   |
    | 002      | Hello   | Mars    |
    | 003      | Goodbye | Mars    |
    +------------------------------+
    Code (markup):
    and I want something like the following output (i.e. row-wise, not col-wise):

    Very long descrip of prim_key: 001 
    Very long descrip of field 1: Hello 
    Very long descrip of field 2: World
     
    Very long descrip of prim_key: 002
    Very long descrip of field 1: Hello 
    Very long descrip of field 2: Mars
     
    Very long descrip of prim_key: 003 
    Very long descrip of field 1: Goodbye
    Very long descrip of field 2: Mars
    Code (markup):
    Why won't the following work? (Oracle 11g)

    for i in ( select prim_key j from data_table ) 
    loop 
       select 'Very long descrip of prim_key:', prim_key 
          from data_table where prim_key = i.j ; 
       select 'Very long descrip of field 1:', field1 
          from data_table where prim_key = i.j ; 
       select 'Very long descrip of field 2:', field2 
          from data_table where prim_key = i.j ; 
    end loop
    Code (markup):
     
    ceemage, Aug 28, 2012 IP
  2. Sarah Reece

    Sarah Reece Greenhorn

    Messages:
    11
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    13
    #2
    The above code should work with small tweaks:a. Use only i in the where clause instead of i.j i.e. from data_table where prim_key = i ;b. Use concatenation - select 'Very long descrip of prim_key:' || prim_key c. Store the result of select statement into a variable, which you may then print.Also, I would suggest that you use only 1 select statement to get the values of all 3 columns (prim_key, field1, field2), instead of 3 separate selects.
     
    Sarah Reece, Aug 30, 2012 IP
    ceemage likes this.
  3. ceemage

    ceemage Well-Known Member

    Messages:
    297
    Likes Received:
    24
    Best Answers:
    0
    Trophy Points:
    110
    #3
    Thanks. With a combination of your suggestions, plus some of my own ideas, I think I've got this sorted now.
     
    ceemage, Aug 31, 2012 IP