且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

引用 SQL Server 中的 2 列主键的外键

更新时间:2023-01-30 11:35:17

当然可以创建与复合(多列)主键的外键关系.您没有向我们展示您用来尝试建立这种关系的语句 - 它应该类似于:

Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:

ALTER TABLE dbo.Content
   ADD CONSTRAINT FK_Content_Libraries
   FOREIGN KEY(LibraryID, Application)
   REFERENCES dbo.Libraries(ID, Application)

这是你用的吗??如果 (ID, Application) 确实是 dbo.Libraries 上的主键,那么这个语句肯定可以工作.

Is that what you're using?? If (ID, Application) is indeed the primary key on dbo.Libraries, this statement should definitely work.

Luk:只是检查一下 - 你能在你的数据库中运行这个语句并报告输出是什么吗??

Luk: just to check - can you run this statement in your database and report back what the output is??

SELECT
    tc.TABLE_NAME,
    tc.CONSTRAINT_NAME, 
    ccu.COLUMN_NAME
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu 
      ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
    tc.TABLE_NAME IN ('Libraries', 'Content')