更换旧游标的更好解决方案?

时间:2012-10-12 16:58:01

标签: sql-server-2008

我有两张这样的表

table1按paymentid排序,paydate:

 paymentid   paydate   amount

  1         20120101    100

  1         20120101    150

  1         20120101    150

  2         20120115    100

  2         20120115    100

...

table2按paymentid排序,paydate:

paymentid    paydate   pay1   pay2   pay3....base on the position from table1...up to pay20

1            20120101   null  null    null   

2            20120115   null  null    null

...

更新后,table2应该是这样的

1            20120101   100   100     150   null.....

2            20120115   100   100     null  null    null.....

到目前为止我可以提出的解决方案是:

1,用于循环通过table1的临时表

2,游标......当前解决方案:

declare @paymentid int 

declare @paydate   char(10)

declare @amount    money

declare @count int

declare @saveid int

declare @savedate char(10)

delcare cur cursor for select paymentid, paydate, amount from table1 order by paymentid, paydate

open cur



fetch next from cur into @paymentid,@paydate,@amount

while @@fetch_status = 0

  if @saveid <> @paymentid or @savedate <> @paydate

     set @count = 1

     set @saveid = @paymentid

     set @savedate = @paydate

  else set @count = @count + 1

  if @count = 1

  update table2 

  set pay1 = @amount

  where paymentid = @paymentid and paydate = @paydate

  if @count = 2

  update table2 

  set pay2 = @amount

  ...

  fetch next

  ...

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

试试这个

SQL Fiddle

declare @Test Table (paymentid int, 
                   paydate varchar(25), amount int)


INSERT INTO @Test

SELECT 1,'20120101',100
UNION ALL
SELECT 1,'20120101',150
UNION ALL
SELECT 1,'20120101',150
UNION ALL
SELECT 2,'20120115',100
UNION ALL
SELECT 2,'20120115',100

--INSERT into Table2 //insert here
SELECT * FROM (
SELECT *, 'pay' + CAST(Row_Number() OVER (Partition by paymentid, 
                        paydate order by amount) AS VARCHAR) PayCol
FROM @Test
)  V
PIVOT 
(
  MAX(Amount) For PayCol IN 
   (pay1,pay2,pay3,pay4, pay5, pay6, pay7, pay8, pay9, pay10,
        pay11,pay12,pay13,pay14, pay15, pay16, pay17, pay18, pay19, pay20)
) As P