SQL Server如何创建多列外键?建表外键语句问题排查
SQL语句问题分析
- 外键引用规则错误:SQL的外键(包括复合多列外键)只能引用单个父表的主键或唯一约束列,不支持同时关联两个不同父表的字段。你语句中
references agente,type_de_verification写了两个父表,不符合语法要求。 - 建表语句语法不完整:整段
CREATE TABLE语句缺少列定义块的闭合右括号),语句结构不合法。 - 逻辑设计错误:从你的写法推测
num_agnt是agente表的主键,code_type是type_de_verification表的主键,这两个字段分属不同父表,不适合合并为一个复合外键,应该分别创建两个独立的单例外键。
正确写法示例
如果两个字段分别关联两个父表,拆分外键即可:
create table visit ( Num_vst int primary key, date_vst date, num_agnt int, code_type int, -- 分别创建两个外键关联对应父表 Constraint fk_vst_agente foreign key (num_agnt) references agente(num_agnt), Constraint fk_vst_codetype foreign key (code_type) references type_de_verification(code_type) );
如果确实需要创建复合外键,必须保证引用的两个列属于同一个父表,且父表已经对这两个列创建了联合主键或者联合唯一约束,示例如下:
-- 假设父表agente已经存在(num_agnt, code_type)的联合唯一约束/联合主键 create table visit ( Num_vst int primary key, date_vst date, num_agnt int, code_type int, Constraint fk_vst_composite foreign key (num_agnt,code_type) references agente(num_agnt,code_type) );
内容的提问来源于stack exchange,提问作者Franklin
相关产品推荐
相关产品推荐

