1. 程式人生 > 其它 >sql server自增主鍵變為非自增,sequence控制id值

sql server自增主鍵變為非自增,sequence控制id值

之前使用的表的主鍵為id自增,現在想變成由sequence來控制id值的增加,不能刪除現有資料,資料一直保持在資料庫中。

之前的schema:

create table biz_job_history (
  id BIGINT identity not null
  , job_id VARCHAR(32)
  , start_time DATETIME2
  , end_time DATETIME2
  , status VARCHAR(32)
  , result NVARCHAR(max)
  , created_date DATE default GETDATE() not null
, created_at DATETIME2 default SYSDATETIME() not null , updated_at DATETIME2 default SYSDATETIME() not null , updated_by VARCHAR(64) not null , constraint biz_job_history_PKC primary key nonclustered (id) ) ;

目標schemal:

create table biz_job_history (
  id BIGINT not null
  , job_id VARCHAR
(32) , start_time DATETIME2 , end_time DATETIME2 , status VARCHAR(32) , result NVARCHAR(max) , created_date DATE default GETDATE() not null , created_at DATETIME2 default SYSDATETIME() not null , updated_at DATETIME2 default SYSDATETIME() not null , updated_by VARCHAR(64) not null ,
constraint biz_job_history_PKC primary key nonclustered (id) ) ; if not exists(select * from sys.sequences where name = N'biz_job_history_seq') create sequence biz_job_history_seq as BIGINT start with 1 increment by 1 no maxvalue go;

不重新建表,僅修改資料庫所需要的操作:

// 新建一列
alter table biz_job_history add id_copy BIGINT not null default 0;
// 之前id的資料儲存到新建的一列
update biz_job_history set id_copy=id;
// 刪除表的主鍵
alter table biz_job_history drop constraint biz_job_history_PKC;
// 刪除id列
ALTER  TABLE biz_job_history DROP column id;
// 將新建的列重新命名為id
exec sp_rename 'biz_job_history.id_copy','id','column'//設定id為表的主鍵
alter table biz_job_history add constraint biz_job_history_PKC primary key nonclustered (id);

// 獲取當前資料id的最大值
select top 1 id from biz_job_history order by created_at desc   --時間倒序排列取第一條

// 使用上一個sql獲取的最大值val,定義sequence的開始值
if not exists(select * from sys.sequences where name = N'biz_job_history_seq')
create sequence biz_job_history_seq as BIGINT
    start with val
    increment by 1
    no maxvalue
go;