使用sql语句实现设置主键自增长列

 
1.新建一数据表,里面有字段id,将id设为为主键 

create table tb(id int,constraint pkid primary key (id))
create table tb(id int primary key )

2.新建一数据表,里面有字段id,将id设为主键且自动编号 

create table tb(id int identity(1,1),constraint pkid primary key (id))
create table tb(id int identity(1,1) primary key )

3.已经建好一数据表,里面有字段id,将id设为主键 

alter table tb alter column id int not null
alter table tb add constraint pkid primary key (id)

4.删除主键 

Declare @Pk varChar(100);
Select @Pk=Name from sysobjects where Parent_Obj=OBJECT_ID('tb') and xtype='PK';
if @Pk is not null
exec('Alter table tb Drop '+ @Pk) 
 
另外方法:
create   table   ttt   
  (   
  t1   int,   
  t2   varchar(8)   
  )   
    
  現在想把字段t1設為自增字段和主鍵.   
    
  那麼運行下面的代碼:   
  CREATE   TABLE   dbo.Tmp_ttt   
  (   
  t1   int   NOT   NULL   IDENTITY   (1,   1),   
  t2   varchar(8)   NULL   
  )   
  go   
  SET   IDENTITY_INSERT   dbo.Tmp_ttt   ON   
  go   
  IF   EXISTS(SELECT   *   FROM   dbo.ttt)   
    EXEC('INSERT   INTO   dbo.Tmp_ttt   (t1,   t2)   
  SELECT   t1,   t2   FROM   dbo.ttt   TABLOCKX')   
  go   
  SET   IDENTITY_INSERT   dbo.Tmp_ttt   OFF   
  go   
  DROP   TABLE   dbo.ttt   
  go   
  EXECUTE   sp_rename   N'dbo.Tmp_ttt',   N'ttt',   'OBJECT'   
  go   
  ALTER   TABLE   dbo.ttt   ADD   CONSTRAINT   
  PK_ttt   PRIMARY   KEY   CLUSTERED     
  (   
  t1   
  )   ON   [PRIMARY]   
  COMMIT   
    
    
  為什麼不用   
  alter   table   ttt   drop   column   t1   
  go   
  alter   table   ttt   add   t1   identity(1,1)   not   null   
  go   
  alter   table   ttt   add   constrain   primary   key   pk_t   (t1)   
  的方法.   
    
  是因為先刪掉一列.再增加一列.   
  那麼列的順序就改變了.   
  有可能帶來意想不到的問題.   
  (比方說,你的程序中有個insert語句是沒有寫字段名的) 
posted @ 2015-07-30 14:15  net5x  阅读(14047)  评论(0编辑  收藏  举报