1

I'm trying to write a stored procedure to return the maximum value of a column + 1 but for some reason it doesn't want to work.

DECLARE @ID int;

SET @ID = SELECT MAX(ID) + 1 FROM tbl;

I can't for the life of me see what is wrong.

It gives me the error of:

incorrect syntax new the keyword 'SELECT'

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Tom
  • 9,725
  • 3
  • 31
  • 48

4 Answers4

4

No need for SET. Select value directly:

DECLARE @ID int;
SELECT @ID = MAX(ID) + 1 FROM tbl;
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
3

Use parentheses ( ... ):

DECLARE @ID int;
SET @ID = (SELECT MAX(ID) + 1 FROM tbl);

or SELECT as suggested by Giorgi. SET is the ANSI standard way of assigning values to variables, SELECT is not. Apart from that using SELECT to assign values to variables is fine, it allows even multiple assignments with one SELECT.

But in general your query seems to be a race condition. Use an IDENTITY column if you want to autoincrement a value. Auto increment primary key in SQL Server Management Studio 2012

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Great thanks a lot - sorry, still thumbing my way through sql – Tom Mar 19 '15 at 15:00
  • @Tom: not sure what you're doing there, but maybe you should use an `Identity` column instead: http://stackoverflow.com/questions/10991894/auto-increment-primary-key-in-sql-server-management-studio-2012 Then this works automatically and you have no race condition. – Tim Schmelter Mar 19 '15 at 15:02
  • I would love to use an identity column, but this table stores lots of versions of the same ID - bad planning when I set it up. – Tom Mar 19 '15 at 15:03
  • 1
    @Tom then you need to fix it. Slapping more code at a known problem is not a good approach. This is going to cause you nothing but pain in the long run. Setup some sequences, create a table for the identity for each type of version or whatever. MAX(ID) + 1 will end up with duplicates and cause nothing but grief....I speak from experience here. – Sean Lange Mar 19 '15 at 15:26
  • I appreciate your points and realise this isn't a good approach but I haven't got the time at the moment to redo the front end of it. I will amend the table in v2.0 – Tom Mar 19 '15 at 15:57
2

You need to consider a scenario when there is no value in the table and MAX returns NULL.

DECLARE @ID int;

SELECT @ID = ISNULL(MAX(ID) , 0) + 1 FROM tbl;

Other adding 1 to null will always yield null.

M.Ali
  • 67,945
  • 13
  • 101
  • 127
1
DECLARE @ID int;
SET @ID = (SELECT MAX(ID) + 1 FROM tbl);

parentheses operator ()

for more information

https://msdn.microsoft.com/en-us/library/ms190276.aspx

Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77