34,837
社区成员




现存的表已经有50000条记录,我需要在这个表的ID字段填充序号(INT类型),填充1到50000,表ID字段默认值是空。代码不知道怎么写
use tempdb
go
if OBJECT_ID('tmp') is not null
drop table tmp
go
create table tmp(
id int,
n nvarchar(10)
)
go
insert into tmp(n)
select left(newid(),10)
go 50000
-- 以上为构建测试表及测试数据
--1 更新
;with cte as (
select
ROW_NUMBER() over(order by (select 1)) as rid
,id
,n
from tmp
)
update cte set id=rid
--2 改为不可为null
alter table tmp alter column id int not null
go
--3 加上主键约束
alter table tmp add constraint PK_tmp primary key (id);
--查询
select * from tmp