我想知道有没有办法做自动循环/计数器批处理,像使用OFFSET / FETCH NEXT方法更新SQL列
问题:下表有20行,我喜欢将DealerId列的前4行更新为1,2,3,4,接下来的4行重复为1,2,3,4值
如下所示 需要修改表
Id DealerId
1 1 1
2 2 2
3 3 3
4 4 4
5 5 1
6 6 2
7 7 3
8 8 4
9 9 1
10 10 2
11 11 3
12 12 4
13 13 1
14 14 2
15 15 3
16 16 4
17 17 1
18 18 2
19 19 3
20 20 4
ORIGINAL TABLE
Id DealerId StoreId TerminalId MessageNo CreatedDate
1 1 86 5027 029500021201403031434350039 2014-03-03 14:34:37.347
2 2 86 5027 029500021201403031434350039 2014-03-05 10:31:59.903
3 3 86 5027 029500021201403031434350039 2014-03-05 10:33:41.293
4 4 86 5027 029500021201403031434350039 2014-03-05 10:46:50.057
5 5 86 5027 029500021201403031434350039 2014-03-05 10:50:23.910
6 6 33 5338 004000003201403051508010255 2014-03-05 15:08:03.247
7 7 26 5595 704201181201403061024330013 2014-03-06 10:24:34.590
8 8 26 5595 704201181201403061026180022 2014-03-06 10:26:19.517
9 9 33 5338 004000003201403061043150312 2014-03-06 10:43:16.013
10 10 86 5027 029500021201403031434350039 2014-03-06 14:27:51.717
11 11 86 5027 029500021201403031434350039 2014-03-06 14:38:40.593
12 12 86 5027 029500021201403031434350039 2014-03-06 14:44:25.947
13 13 521 4905 051100003002447 2014-03-07 12:51:07.487
14 14 521 4905 051100003002447 2014-03-07 12:55:07.300
15 15 521 4905 051100003002447 2014-03-07 12:56:24.793
16 16 521 4905 051100003002447 2014-03-07 12:57:43.123
17 17 521 4905 051100003002447 2014-03-07 14:15:11.093
18 18 632 5120 088800003201403071441280026 2014-03-07 14:41:29.733
19 19 632 5120 088800003201403071456500050 2014-03-07 14:56:51.727
20 20 632 5120 088800003201403071459240064 2014-03-07 14:59:24.953
答案 0 :(得分:0)
假设所有id都是,从1开始:
在MySQL中:
update OriginalTable
set DealreId = mod(id-1, 4)+1
并在Microsoft SQL Server中:
update OriginalTable
set DealreId = ((id-1)%4)+1
答案 1 :(得分:0)
如果id不是(或者不是从1开始),你可以使用游标逐个更新它:
DECLARE c1 CURSOR FOR
SELECT id, dealerId
FROM OriginalTable
ORDER BY id, dealerId
OPEN c1
declare @id int
declare @dealerId int
declare @i int
set @i = 1
FETCH NEXT FROM c1
INTO @id, @dealerId
while @@FETCH_STATUS = 0
BEGIN
update OriginalTable
set dealerId = @i
where current of c1
if (@i < 4)
set @i = @i + 1
else
set @i = 1
FETCH NEXT FROM c1
INTO @id, @dealerId
END