0

有没有办法用从 1 开始的升序数字填充一个空列,而不使用标识?

我尝试了以下游标,但它为列中的所有行填充相同的值(450):

declare cur3 cursor for
select new_id from sheet1$
declare @no int
declare @no1 int
set @no1 = 1
open cur3
fetch next from cur3 into @no
while(@@FETCH_STATUS = 0)
begin
update sheet1$ set new_id = @no1
set @no1 = @no1 + 1
fetch next from cur3 into @no
end
close cur3
deallocate cur3
4

2 回答 2

3

问题是您WHERE在更新查询中缺少一个子句,因此每个循环都在更新所有行。它应该是:

UPDATE  sheet1$ 
SET     new_id = @no1
WHERE   New_ID = @No    -- ONLY UPDATE 1 ROW

顺便说一句,假设您的 SQL-Server 标记是正确的,您可以使用ROW_NUMBER()函数在没有光标的情况下执行此操作

WITH CTE AS
(   SELECT  New_ID, [RN] = ROW_NUMBER() OVER(ORDER BY New_ID)
    FROM    yourTable
)
UPDATE  CTE
SET     New_ID = RN

编辑 - 解释

ROW_NUMBER 只是提供了一个数字序列,Common Table Expression就像一个动态视图:

If you run:

WITH CTE AS
(   SELECT  New_ID, [RN] = ROW_NUMBER() OVER(ORDER BY New_ID)
    FROM    yourTable
)
SELECT  *
FROM    CTE

您应该更好地了解 CTE 中正在做什么,那么 CTE 的美妙之处在于您可以直接更新它们而无需参考回原始表,因此更新 CTE 相当于:

UPDATE  yourTable
SET     New_ID = RN
FROM    yourTable
        INNER JOIN
        (   SELECT  New_ID, [RN] = ROW_NUMBER() OVER(ORDER BY New_ID)
            FROM    yourTable
        ) n
            ON n.New_ID = yourTable.New_ID;
于 2012-11-06T17:50:35.483 回答
1

是的,ROW_NUMBER

像下面这样使用:

select ROW_NUMBER()OVER(ORDER BY Somefield) As Id
      ,*
  from SomeTable

您可以阅读所有相关信息:http: //msdn.microsoft.com/en-us/library/ms186734 (v=sql.105).aspx

于 2012-11-06T17:49:05.123 回答