Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get next ID upon INSERT?

I want to make sure the ID column is incremented for every insert on a table.

I tried this statement:

INSERT INTO Anlagenteil (ID, TaId, Subtype, Name)
VALUES                  (MAX(ID)+1, 0, 'BdAnlageteil', 'Barcodeleser0');

Unfortunately I get this error message:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'ID'.
like image 218
BetaRide Avatar asked Jul 03 '13 09:07

BetaRide


People also ask

How do I SELECT next id in SQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.

How can I get auto increment value after insert?

Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.

How do you get the ID of the inserted row in SQL?

@@IDENTITY returns the id of the last thing that was inserted by your client's connection to the database. IDENT_CURRENT returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.


1 Answers

Use nested query like this:

INSERT INTO Anlagenteil (ID, TaId, Subtype, Name)
VALUES ((SELECT ISNULL(MAX(ID) + 1, 1) FROM Anlagenteil), 0, 'BdAnlageteil', 'Barcodeleser0');
like image 186
Himanshu Jansari Avatar answered Sep 23 '22 00:09

Himanshu Jansari