使所有行都有单调的字段

时间:2010-10-11 10:49:09

标签: sql sql-server-2008

我的sql server数据库中有表,我想将其转换为PK列

为此,我想将此列中每行的值更改为1,2,3 ...

你能为该任务编写T-Sql查询吗?

感谢您的帮助

开始状态:

Id | Name |
----------
1  | One  |
2  | Two  |
2  | Three|
x  | xxx  |

结果:

Id | Name |
----------
1  | One  |
2  | Two  |
3  | Three|
4  | xxx  |

2 个答案:

答案 0 :(得分:4)

;with cte as
(
SELECT Id, ROW_NUMBER() over (order by Id) as rn
from YourTable
)
UPDATE cte SET Id = rn

答案 1 :(得分:0)

如果你没有id,你也可以用名字来做它!

;with cte as
(
SELECT Id, ROW_NUMBER() over (order by name) as rn
from YourTable
)
UPDATE cte SET Id = rn