开发者

Looping thru columns in SQL server 2008

I have a table with structure

TableA
    ID   price1   price2 price3 pri开发者_运维知识库ce4 rate1 rate2 rate3 rate4
    1     10       11     12      13    2     3      2     2

i want to insert into another tableB

ID   Price Rate
 1    10    2
 1    11    3

Now in my cursor i am fetching all the values from TableA into variables

Fetch next from cursor1 into @id,@price1,@price2,@price3,@price4,@rate1,@rate2,@rate3,@rate4

After fetching it i want to insert into TableB

I want to loop through columns of the TableA so the insert statement is

 insert into tableB (Id,Price,Rate) values (@id,@price1,@rate1)

But i would have to give 4 insert statement to get the values

Is there a way i can loop so i can have one single insert statement in a loop

In this example i had given just 4 columns but i have 30 columns so its essential i need to get into loop

Thanks

Prady


You dont need cursors for this, it can be done straight from a query -

INSERT INTO TableB (id, price, rate)
select id, price1, rate1 from TableA
UNION ALL
select id, price2, rate2 from TableA
UNION ALL
select id, price3, rate3 from TableA
..
..

Avoid cursors if possible, they always have performance impact.


The syntax you are looking for is:

INSERT INTO TableB (ID, Price, Rate)
VALUES
(@id, @price1, @rate1),
(@id, @price2, @rate2),
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜