有没有办法用一个从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
答案 0 :(得分: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;
答案 1 :(得分: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