View Single Post
  #3 (permalink)  
Old 01-23-2007, 03:30 AM
Dimitar
 
Posts: n/a
Default ANY answer. Re: How to select highest value and then create new object with that value +1?

This should work it most dialects:
[sql]
insert into item (iid) select max(iid) +1 from item;
[/sql]
I find it simpler, but it assumes the IID column is defined NOT NULL.
Here is another attempt, which does not make that assumption:
[sql]
insert into item (iid) select max(case when iid is null then -1 else iid end) +1 from item; [/sql]
But what if the table is initially empty?
As the function MAX is applied to an empty set, it will return the null value, which will become the value of the first IID.
Let us again consider the first version (with the NOT NULL assumption):
[sql]
nsert into item (iid) select case when hm is null then 0 else hm end from (select max(iid) + 1 from item ) as t
[/sql]
Edit/Delete Message Reply With Quote