how to write a sql script that cursors through a table and inserts into a different table?

One method uses cross apply to unpivot the columns of the unnormalized table to rows, then brings the items table with a join, and finally inserts in the target table:

insert into ImportItems_Summary (code, items_id, import_total)
select im.code, it.items_id, x.import_total
from import im
cross apply (values 
    ('socks',  sockstotal),
    ('gloves', glovestotal),
    ('jeans',  jeanstotal),
    ('shirts', shirtstotal),
    ('shoes',  shoestotal)
) x(item, import_total)
inner join items it on it.item = x.item

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top