Question

First at all, sorry for my english. I've tried to find an answer to this question but I don't really how to express myself.

If it's a duplicate, please close it and let me know the answer.

I have a table to store the data for each item of customer's shopping cart. The structure is:

Table - tmpShoppingCartItem

tmpShoppingCart_ID  int FK from tmpShoppingCart
ID                  int PK, Ident 1,1
StoreSKU_ID         int FK from StoreSku
Quantity            int 
Enabled             bit 

The column ID is a identity with seed = 1. But when I start inserting data, it looks like:

tmpShoppingCart_ID        ID          ....
1                         1
1                         2
1                         3
1                         4

until here, its ok but when it's a new shopping cart, it looks like:

tmpShoppingCart_ID        ID          ....
2                         5
2                         6
3                         7
4                         8

the ID columns still seeding 1.

I want to know if (and how) can I reset the seed counter when the tmpShoppingCart_ID changes, like:

tmpShoppingCart_ID        ID          ....
1                         1
1                         2
1                         3
1                         4
2                         1
2                         2
3                         1
3                         2
3                         3
3                         4
3                         5
4                         1

Thanks for your time.

Était-ce utile?

La solution

Identity columns when used as a primary key should be sequential and not repeat in a table. First, you need to make both temShoppingCart_ID and ID the unique PK to prevent duplicatation. Secondly, you will not be able to use the IDENTITY function, but rather a counter in your application for each row that's inserted for a given tempShoppingCart_ID.

In my opinion, keep the ID as an identity column like it currently is. Add a second column called LineID and make that increment per record.

Autres conseils

You cannot do that with an auto incrementing field. If you want to do that you will have to write a trigger to popluate the field based on a process you write. The process will have to make sure it includes multiple row inserts and can handle race conditions. WHy do you want to do this? Are you planning on letting customers reorder the shopping cart ids. THey don't need to ever see the id so it should not matter if the first on is 1 or 7.

I do want to point out that while DBCC CHECKIDENT ([Table_Name], RESEED, 0) might technically work, it requires the user to be a sys_admin or db_owner or db_ddladmin. None of these are roles that should ever be assigned to the user who logs in from an application to do data entry.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top