Only allow one of two columns to be set

本小妞迷上赌 提交于 2019-12-11 22:34:18

问题


I'm looking for a constraint in an SQL table that will only allow one of two nullable columns to be set per row. Both columns are foreign keys that relate to different tables.

As an example, say each table row describes a section of a journey. I have a separate table for Cars and Planes.

Without redesigning my whole database to use a Vehicles table, how can I ensure that each journey row is done by either a CarID or a PlaneID, but never both at the same time, and never neither?


回答1:


Add a constraint something like this...

ALTER TABLE TableName
ADD CONSTRAINT ck_Nullable CHECK (
                                    (CarID IS NULL AND PlaneID IS NOT NULL)
                                   OR 
                                    (CarID IS NOT NULL AND PlaneID IS NULL)
                                 )


来源:https://stackoverflow.com/questions/25138805/only-allow-one-of-two-columns-to-be-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!