ibmi-brunch-learn

Announcement

Collapse
No announcement yet.

a way to insert from a range of rows

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • a way to insert from a range of rows

    I'm needing to do an insert (selecting rows from another table), but only want to specify a certain range of rows.

    If I do this...

    select * from
    (select dsln, row_number() over() as rownumber
    from ldatacpd.srvdtrn) as column
    where rownumber between 1 and 3

    then i am able to select the rows from the source table as desired.

    However if I want to morph that into an insert statement such as the following, i run into issues.

    insert into ls#jhv.srvdtrn (dsln)
    (select * from
    (select dsln, row_number() over() as rownumber
    from ldatacpd.srvdtrn) as column
    where rownumber between 1 and 3)

    Any suggestions on how to restructure and overcome?

    Guess I could always build a cursor from the row numbers selected then do individual inserts for each row, but I'm looking for the best performance option.




  • #2
    It is because your outer select query is returning two fields - dsln and rownumber, but the insert is expecting only one (dsln)

    Try this (difference in bold)
    insert into ls#jhv.srvdtrn (dsln)
    (select dsln from
    (select dsln, row_number() over() as rownumber
    from ldatacpd.srvdtrn) as column
    where rownumber between 1 and 3)

    If you only want the first three rows (as you have coded) as opposed to any random range of rows, then you could also do this:
    insert into ls#jhv.srvdtrn (dsln)
    (select dsln from ldatacpd.srvdtrn
    fetch first 3 rows only) as column

    Comment

    Working...
    X