SQL现存的表在某字段填充序号

不素之霸 2024-12-12 23:52:38

现存的表已经有50000条记录,我需要在这个表的ID字段填充序号(INT类型),填充1到50000,表ID字段默认值是空。代码不知道怎么写

...全文
247 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
吉普赛的歌 版主 2024-12-13
精选
  • 打赏
  • 举报
回复 1
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

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧