Increase Id with an INSERT in SQL Server

1

I have a table with different fields, I want to do a INSERT in which the new sentences have the Id from the last one.

How could I do it?

I thought about doing something like this:

insert into id = id + 1

But I'm not convinced that it works, they could help me.

    
asked by CMorillo 22.08.2017 в 09:41
source

4 answers

1

You have to go to the structure tab and to your column id put the autoincrement attribute.

So when you do a INSERT INTO mitabla (nombre) VALUES ('pepe') the id of that line will autoincrementá.

It is not correct to set the id by hand because mysql has hidden data and things of its own to optimize the queries: S

An example to mark an auto-incremental id:

CREATE TABLE Persons (
    ID int NOT NULL AUTO_INCREMENT,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);
    
answered by 22.08.2017 / 09:53
source
3

In order to insert a Id incremental auto, the best practice is to define it in the table with the property IDENTITY :

CREATE TABLE Tabla (
    Id           INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    Descripcion  VARCHAR (64) NULL
    -- Aquí va la definición de los demás campos
);

To make the INSERT , simply omit the Id field, since internally the autoincrementable part is performed:

INSERT INTO Tabla (Descripcion) VALUES ('Alguna descripción con Id 1')
INSERT INTO Tabla (Descripcion) VALUES ('Alguna descripción con Id 2')

The result will be as follows:

+----+-----------------------------+
| Id | Descripcion                 |
+----+-----------------------------+
| 1  | Alguna descripción con Id 1 |
+----+-----------------------------+
| 2  | Alguna descripción con Id 2 |
+----+-----------------------------+

Here you can see the demo and its results .

    
answered by 22.08.2017 в 20:03
2

This could be an example, but as you say in the comments, the most important thing is to try and try (This is how you learn more)

   INSERT [INTO] nombreTabla (id, atributo, atributo2)
     VALUES ((SELECT TOP 1 id FROM nombreTabla ORDER BY id DESC)+1, "atributo1", "atributo2");

Also in the creation of the table there is the AUTO-INCREMENT an example:

CREATE TABLE Personas (
    ID int IDENTITY(1,1) ,
    nombre varchar(30) NOT NULL,
    apellidos varchar(30),
    nif varchar(24),
    PRIMARY KEY (ID)
);

And when inserting in the table it is not necessary to tell the ID :

INSERT Personas (lastName,firstName,nif) VALUES ("Juan", "Gonzalez", "00000000X");
    
answered by 22.08.2017 в 10:00
-1

You can also put your serial type ID like this:

 CREATE TABLE Personas (
    ID serial,
    nombre varchar(30) NOT NULL,
    apellidos varchar(30),
    documento varchar(24),
    PRIMARY KEY (ID)
);
    
answered by 22.08.2017 в 18:35