I use the same instance of the database to service multiple customers. The customer ID is an int generated through @@IDENTITY. This table looks like:
CUSTOMER
customer_id int,
...
I want all other tables to have customer_id as part of a compound key. For example, the table to store people would look like this:
PERSON
customer_id int,
person_id int,
...
Now here comes the hard bit. For each customer_id, I want the person_id to start with 1. For example:
customer_id: 1, person_id: 1
customer_id: 1, person_id: 2
customer_id: 1, person_id: 3
customer_id: 2, person_id: 1
customer_id: 2, person_id: 2
I've considered a solution like adding a column to CUSTOMER table such as "next_person_id". Then the application would get this value and increment it by 1. But there is a concurrency problem. When 10 threads try to read and update next_person_id field at the same time, the value in this field is incorrect. Instead of 11, you get 6 or 7.
Anyone have an idea of how I can create these compound keys?
CUSTOMER
customer_id int,
...
I want all other tables to have customer_id as part of a compound key. For example, the table to store people would look like this:
PERSON
customer_id int,
person_id int,
...
Now here comes the hard bit. For each customer_id, I want the person_id to start with 1. For example:
customer_id: 1, person_id: 1
customer_id: 1, person_id: 2
customer_id: 1, person_id: 3
customer_id: 2, person_id: 1
customer_id: 2, person_id: 2
I've considered a solution like adding a column to CUSTOMER table such as "next_person_id". Then the application would get this value and increment it by 1. But there is a concurrency problem. When 10 threads try to read and update next_person_id field at the same time, the value in this field is incorrect. Instead of 11, you get 6 or 7.
Anyone have an idea of how I can create these compound keys?