Consecutive to INSERT

0

I have this query

INSERT INTO [SI_Consecutivo] 
(SI_Num_Inventario, SI_Nombre, SI_Fecha_Creacion, SI_Estado, SI_Almacen, SI_Num_Conteo) 
VALUES (1, 'uno',  GETDATE(), 0,'cdis', 1 + FLOOR(RAND() * 1 ))

I execute it with a button in javascript. what I'm trying to do is that when I insert in the field SI_Num_Conte I keep it as if it were a consecutive, that is, I will stay 1, if I give it again in the button I save what I saved above + 1 , and so on until the end of time.

    
asked by Eduard 22.06.2017 в 22:04
source

2 answers

1

If you change the field to identity, there may come a time when the number is not consecutive due to some transaction that does not end or some other factor of that type, identity should not be used for this purpose. On the other hand if you want to have a consecutive value in each new field I would recommend a

INSERT INTO [SI_Consecutivo] 
(SI_Num_Inventario, SI_Nombre, SI_Fecha_Creacion, SI_Estado, SI_Almacen, SI_Num_Conteo) 
VALUES (1, 'uno',  GETDATE(), 0,'cdis', (SELECT MAX(SI_Num_Conte)+1 FROM SI_Consecutivo ))

or even create a function with the same query

SELECT MAX(SI_Num_Conte)+1 FROM SI_Consecutivo 

and send to call the function in each insert

    
answered by 23.06.2017 / 22:17
source
2

The best thing you can do is let the database engine do the work for you. How to achieve it varies according to the engine you are using but since your label is for SQL Server my explanation will be for it:

  

When you create a new table, you must define the field with the property IDENTITY , in which you define first the value with which it will start and secondly the increase it will have.

The specific instruction is:

CREATE TABLE Blahblah(
    ID INT IDENTITY(1, 1) PRIMARY KEY,
    Field1 ..., FieldN ...)

where (1, 1) means starts at 1 and increments one at a time . If you wanted, for example, to jump from 2 to 2, it would be IDENTITY(1,2) or if you want it to start at 100 it would be IDENTITY(100, 1) . In this way you avoid making extra queries to the databases, you give integrity and you get what you need.

Always look for ways to modulate tasks, make each part of your system do the same to get the best.

Finally, I'll leave you some liks about it:

answered by 22.06.2017 в 23:32