简体   繁体   中英

Create a sql foreign key constraint

I wish to create a constraint that state as below

Code.CodeTable ( CodeID smallint, CategoryID smallint,....)  --> Parent Table
Admin.Document( DocumentTypeID smallint,.....)  --> Child Table

The FK will be Admin.Document.DocumentTypeID map with Code.CodeTable.CodeID

I wish to have the constraint that only check Code.CodeTable.CodeID which the Code.CodeTable.CategoryID = 15 only.

As OMG Ponies already said - you cannot create fk constraints across databases, but if those are just odd table names with dots in them (highly discouraged! since SQL Server already uses a dotted schema: (database).(schema).(object name) and thus having dots in your table names is just asking for trouble at some point....), then you should be able to create your constraint like this:

ALTER TABLE [Admin.Document]
  ADD CONSTRAINT FK_AdminDocument_CodeTableCodeID
  FOREIGN KEY(DocumentTypeID) REFERENCES [Code.CodeTable](CodeID)

Since you have dots in your table names, you need to enclose those names in square brackets [].

Basically, you need to modify the child table and tell SQL Server which column in that child table refers to what parent table and column in the parent table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM