I’m working in SQLAzure at the moment.
I’m setting up a design where each User has a number of Address’s
When the user then places an Order, then I want to link that Order to both the User and to a couple of Addresses.
So my tables look like:
User
- Id
- Name
- etc
Address
- Id
- UserId (Foreign Key)
- Street
- etc
Order
- Id
- UserId (Foreign Key)
- DeliveryAddressId (Foreign Key)
- BillingAddressId (Foreign Key)
- etc
Is there a way I can I set up a check within SQL Server so that a user can’t under any circumstances (e.g. by hacking an HTML POST) submit an Order with an AddressId which is not linked to the same as the submitted UserId. I’ve looked at “foreign key constraints” in the docs, but this doesn’t seem to be quite what I’m looking for.
Any suggestions of what to try – or what tutorials to read – would be most appreciated.
In addition to your primary key in the Address table (on Id), you should also declare another key constraint, a UNIQUE constraint, on (Id,UserId).
You can then either replace your existing FKs from Order to address, or add additional ones, that check both columns
As I say, you can add these all as additional constraints, if you want to.
So, with some slight naming tweaks, your tables are rendered as this:
And trying it our with some inserts that should work, except for the last (where there’s a user/address mismatch), it works:
Results: