SQL-Server 2008:如何使用计数器更新字段?

时间:2012-05-25 09:59:33

标签: sql sql-server sql-server-2008

在PostgrSQL上,我这样做没问题:

CREATE SEQUENCE serial_olw START 1;
update collections_elements set elementorder=(nextval('serial_olw')-1) WHERE collections_elements.collectionid=1;
drop sequence serial_olw;

示例:1,2,3,4,5,6 ......

在MS-SQL Server 2008上没有SEQUENCE函数...所以我尝试了这个:

DECLARE @i int
SET @i = 0

WHILE @i<44
    BEGIN
    UPDATE collections_elements set elementorder=(@i) WHERE collections_elements.collectionid=1
        SET @i=@i+1
    END

但我对那个循环没有成功......

示例:43,43,43,43,43 ......

解决方案的任何想法?

4 个答案:

答案 0 :(得分:2)

Update t
Set t.elementorder = t.RowID
From
(
    Select ROW_NUMBER() Over(Order by collectionid) as RowID, * From collections_elements
)t

<强> SQL Fiddle

答案 1 :(得分:1)

update T
set elementorder = rn
from
  (
    select elementorder,
           row_number() over(order by (select 0)) as rn
    from collections_elements
    where collectionid = 1
  ) T

SE-Data

答案 2 :(得分:0)

尝试这样的事情 - 内联变量增量:

DECLARE @i int 
SET @i = 0

WHILE @i<44 
BEGIN
    UPDATE collections_elements 
    SET @i = elementorder = @i + 1 
    WHERE collections_elements.collectionid=1 
END

答案 3 :(得分:0)

此脚本是一个示例。 尝试这样的事情-内联变量增量:

ThreadPool