sql loop with insert

  • I've placed data into a temp table as such:

    declare @i as int

    declare @nmbrRow as int

    declare @dM table(dM varchar(max))

    insert @dM (select lname from names etc..)

    set @nmbrRow = (select count(*) from @dM ) -- returns 2 which is the exact row count in the temp table

    set @i = 0

    select dM from @dM --will return the below table:

    dM

    ----

    lastName1

    lastName2

    What I need to figure out is how to loop through the temp table (@dM) and insert each row element into another table. I thought this would work but it clearly fails.

    while @i < @nmbrRow

    begin

    insert into lastNames (param1,L,S,lname)

    values (@param1, '0', '0', (select dM from @dM))

    end

    How should I go about inserting each row from the @dM temp table into the insert command?

  • wdmm (4/28/2016)


    I've placed data into a temp table as such:

    declare @i as int

    declare @nmbrRow as int

    declare @dM table(dM varchar(max))

    insert @dM (select lname from names etc..)

    set @nmbrRow = (select count(*) from @dM ) -- returns 2 which is the exact row count in the temp table

    set @i = 0

    select dM from @dM --will return the below table:

    dM

    ----

    lastName1

    lastName2

    What I need to figure out is how to loop through the temp table (@dM) and insert each row element into another table. I thought this would work but it clearly fails.

    while @i < @nmbrRow

    begin

    insert into lastNames (param1,L,S,lname)

    values (@param1, '0', '0', (select dM from @dM))

    end

    How should I go about inserting each row from the @dM temp table into the insert command?

    This?

    insert into lastNames (param1,L,lS,lname)

    select @param1,'0','0',dM from @dM;

  • Thanks, Lynn - not sure how I over thought that....

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply