8

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'.
Himanshu
  • 31,810
  • 31
  • 111
  • 133
BetaRide
  • 16,207
  • 29
  • 99
  • 177
  • 3
    If you need incrementing values, it's usually better to use the built in features (in SQL Server, that would be an [`IDENTITY`](http://msdn.microsoft.com/en-us/library/ms186775.aspx) column). Consider what happens with your approach if two users run the same code at the same time. – Damien_The_Unbeliever Jul 03 '13 at 09:52

2 Answers2

14

Use nested query like this:

INSERT INTO Anlagenteil (ID, TaId, Subtype, Name)
VALUES ((SELECT ISNULL(MAX(ID) + 1, 1) FROM Anlagenteil), 0, 'BdAnlageteil', 'Barcodeleser0');
Neville Nazerane
  • 6,622
  • 3
  • 46
  • 79
Himanshu
  • 31,810
  • 31
  • 111
  • 133
4

Invalid column name 'ID'.

This suggests you don't have an ID column at all.

You should add this column to the table, and set it to auto-increment, rather than writing the logic to do this yourself.

As @Damien_The_Unbeliever has pointed out, this could cause issues if 2 people run the script at the same time.

ALTER TABLE Anlagenteil
ADD ID INT IDENTITY(1,1)

Then your SQL statement can just be:

INSERT INTO Anlagenteil (TaId, Subtype, Name)
VALUES                  (0, 'BdAnlageteil', 'Barcodeleser0')

And the new ID value will automatically be added.

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
  • 1
    ID is definitely a valid column name. – BetaRide Jul 03 '13 at 09:58
  • Important note, [to ensure unique values generated for an IDENTITY column](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-ver16#remarks), the column must be a primary key, a unique key, or unique constraint. Simply making a column an identity column is not enough to guarantee uniqueness. – TT. Mar 21 '23 at 07:29