请问如何给已有表添加一个新的外键列呢?用语句怎么写呢

解决方案 »

  1.   

    alter table tb add sid int not null
    goalter table tb add constraint fk_name_1 foreign key([sid])
    references [dbo].[newtable] ([id])
    go
      

  2.   

    alter table tb add constraint 外键约束名 foreign key(外键列名) references 外键引用表 (主键列)
      

  3.   

    alter table tb add sid int not null
    goSQL codealter table tb add constraint 外键约束名 foreign key(外键列名) references 外键引用表 (主键列) 
      

  4.   

    先add这个列,然后再添加外键约束,楼上的很对!
      

  5.   

    ---创建主键约束,唯一约束,检查约束
    create table test
    (
      id int,
      testname varchar(50),
      sex bit,
      class varchar(50),
      score float default(0)
      constraint pk_test primary key/*这里可以指定是创建聚集或非聚集索引clustered|nonclustered可选项*/(id)
      constraint ix_test unique(testname)
      constraint ck_test check/*这里可以使用 not for replication可选项,用于指定当从其他表中复制数据时,不检查约束条件*/(score>=0)
    )
      go
    alter table tb
    add constraint pk_tb primary key nonclustered (id)
    goalter table tb
    add constraint ck_sex check(sex='男' or sex='女')
    go---创建和使用默认约束
    alter table tb
    add constraint de_test default'test' for test  ---在表tb的列test的默认约束为'test'
    go--创建和使用外键约束
    alter table tb
    add constraint fk_tb_tb1 foreign key(id)
    references tb1(id)
    go