注册 登录
编程论坛 SQL Server论坛

怎么用SQL语句设外键

toutou1231 发布于 2007-11-02 21:36, 23460 次点击

在表建好后 SQL语句怎么写设外键

查了下
alter table table2 add constraint fk_one foreign key (id)
references table1 (id)

fk_one 这里是什么意思 第一个外键

PS; 主键一定要建表的时候设吗 可以跟外键一样 用SQL语句设吗 ?可以的话 怎么写?

谢谢

5 回复
#2
purana2007-11-03 10:18
设置主键.
alter table table2 add constraint fk_key primary key (id)
#3
purana2007-11-03 10:18
fk_one
就是一个约束名.
#4
缘吇弹2007-11-03 12:01
以下是引用toutou1231在2007-11-2 21:36:59的发言:

在表建好后 SQL语句怎么写设外键

查了下
alter table table2 add constraint fk_one foreign key (id)
references table1 (id)

fk_one 这里是什么意思 第一个外键

PS; 主键一定要建表的时候设吗 可以跟外键一样 用SQL语句设吗 ?可以的话 怎么写?

谢谢

要想你上边的那句生效,table1的id字段必须要设为主键,要不table2怎么参照?
像设置外键那样设置主键的方法2楼的版主已经说了.

#5
雪雨星风2007-11-23 12:48
alter    table     city         --表city
add    constraint   fk_city_prov         --表city和表prov
foreign    kiy(prov_id)ref   erences   s   (prov_id)
#6
orliubc2007-11-23 15:02
一般来说主键、外键,以及各表之间的关系在数据库结构分析阶段就已经分析确定好了,
做好之后再改的情况基本不常见。要不做项目要累死了。
建表时直接确定关系。
Create table table1
(oneID int identity(1,1) Primary Key,          --主键列
oneName varchar(20) Not Null
)
Create table table2
(twoID int identity(1,1) Primary Key,                       --主键列
oneID int Foreign Key References table1(oneID),          --外键列,级联table1(oneID)
twoAddress varchar(50) Not Null
)
1