简体   繁体   中英

TSQL :how to reset the value of identity column in a table?

Is possible to reset the automatic value every time change the value of another column ?

I have a classic database INVOICES with two tables related (one-to -many), HEAD and LINES .

Table HEAD : ID_TESTA , CUSTOMER ... etc (the column ID_TESTA is PK and also is identity)

table LINES : ID_TESTA , ID_RIGA , ITEM, PRICE , etc. ... ( columns ID_TESTA and ID_RIGA are togheter the composed PK , and the column ID_RIGA is also an identity. This column ID_RIGA should reset with each change of ID_TESTA value.

Example: now the table LINES it's like this:

1 1 Article 100 €
1 2 piece  30 €
2 3 nails   40 euro
2 4 screws  50 €
2 5 wood    47 €
3 6 rows    38 €
3 7 crane   6 € 

I wish it so :

1 1 Article 100 €
1 2 piece  30 €
2 1 nails   40 euro
2 2 screws  50 €
2 3 wood    47 €
3 1 rows    38 €
3 2 crane   6 € 

In TSQL INSERT statements that feed the tables , I dont write the identity columns , they are automatically assigned by the database.

Bye Bye Tank you

Just do this when you query on the table:

select l.*, row_number() over (partition by id_testA order by id_riga) as seqnum
from lines l;

You can put this into a view so it is available wherever the table is used.

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