我建了一个表
create table(a varchar(10) primary,b varchar(10)
现在如何修改 a b同时为主键?

解决方案 »

  1.   

    --删除主键
    alter table 表名 drop constraint 主键名
    --添加主键
    alter table 表名 add  constraint 主键名 primary key(字段名1,字段名2……)
      

  2.   

    create table T(
    a varchar(10) not null constraint PK_T primary key,
    b varchar(10) not null

    alter table T
    drop constraint PK_Talter table T
    add constraint PK_TT primary key (a,b)
      

  3.   

    一个表只能有一个 PRIMARY KEY 约束
      

  4.   

    create table testCol (a varchar(10)  , b varchar(10))
    goinsert into testCol 
    select 'a' , 'aa' union
    select 'b' , 'bb' union
    select 'c' , 'cc' 
    go
    -- 备份b列数据
    alter table testCol ADD c  varchar(10)
    go
    update testCol set c = b
    go
    -- 删除b列
    alter table testCol DROP COLUMN b
    go
    --重新创建 b列
    alter table testCol ADD b  varchar(10) primary key
    go
    --恢复数据
    update testCol set b = c
    go
    --删除备份列
    alter table testCol DROP COLUMN c
    go