简体   繁体   中英

SQL Server Check Constraint querying other tables

I have a table called Address which has a not-null CityID column and a nullable DistrictID column.

I want to make sure that if a district is entered to the table the district is indeed a district of the spesific city. Can I do that with a Check Constraint?

My table structure is as follows:

City: CityID (int), Name(nvarchar)

District: DistrictID (int), CityID (int), Name(nvarchar)

Address: AddressID (int), CityID(int), DistrictID(int)

If it is not doable with a check constraint I would like to see the trigger solution as well.

A composite foreign key containing both cityid and districtid would provide this check.

ALTER TABLE Address
ADD FOREIGN KEY (districtid, cityid) REFERENCES district(districtid, cityid)

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