gpt4 book ai didi

sql - 在 SQL Server 2008 中创建复合外键

转载 作者:行者123 更新时间:2023-12-03 09:00:35 24 4
gpt4 key购买 nike

我有两个要为其创建外键的表。

主表

PK - Key1 - varchar(20)
PK - Key2 - date

二级表
PK - AutoID
FK - Key1 - varchar(20)
FK - Key2 - date

当我尝试在主表和辅助表之间创建关系时,我不断收到消息

The columns in the Primary Table do not match a primary key or unique constraint.



辅助表中可以有许多具有相同 Key1 和 Key2 的记录,因此我们将主键设置为自动创建的数字。

关于如何在这两个表之间设置外键关系的任何想法?

最佳答案

外键必须引用组成唯一索引(PK 或 UK)的列,具有相同的列数、类型和顺序。例如。:

CREATE TABLE PrimaryTable (
Key1 varchar(20),
Key2 date)
GO

ALTER TABLE PrimaryTable ADD CONSTRAINT PK
PRIMARY KEY (Key1, Key2)
GO

CREATE TABLE SecondaryTable (
AutoID int IDENTITY,
Key1 varchar(20),
Key2 date)
GO

ALTER TABLE SecondaryTable ADD CONSTRAINT FK
FOREIGN KEY (Key1, Key2) REFERENCES PrimaryTable (Key1, Key2)
GO

关于sql - 在 SQL Server 2008 中创建复合外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6651667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com