简体   繁体   中英

select max value of a column in table with no rows

I am using oracle database

While inserting a row in a table, i need to find the max value of a column and increment it by 1, and use that value in row i am inserting.

INSERT INTO dts_route 
   (ROUTE_ID, ROUTE_UID, ROUTE_FOLDER)
VALUES (
                        (SELECT MAX(ROUTE_ID) + 1 FROM  route) ,
                        ROUTE_UID,
                        ROUTE_FOLDER)

This works fine if their is at least one entry in table. But returns null when their are no entries in table.

How can i get default value of 1 when their are no entries in table.

SELECT COALESCE(MAX(ROUTE_ID),0) ...

This is not a safe way of creating an auto-increment field. You can use an Oracle sequence to achieve this goal.

As for the null, you can use NVL to give a default value (say, 0) in case the function returns null.

Use sequence for the ID. You need to create sequence. See below link

http://www.basis.com/onlinedocs/documentation/b3odbc/sql_sequences.htm

Use:

INSERT INTO dts_route 
   (ROUTE_ID)
SELECT COALESCE(MAX(r.route_id), 0) +1
  FROM ROUTE r

...but you really should be using a sequence to populate the value with a sequential numeric value:

CREATE SEQUENCE dts_route_seq;

...

INSERT INTO dts_route 
   (ROUTE_ID)
SELECT dts_route_seq.NEXTVAL
  FROM DUAL;

Set a default for NULL

SELECT NVL(MAX(ROUTE_ID),0)

though using a sequence might be easier if you don't mind the odd gaps in your route ids

select 0 when null, then it will be 0+1 which is a correct number compared to null+1

SELECT isnull(MAX(ROUTE_ID),0) + 1 FROM route

If you are concerned about there being gaps in your route ids then create the sequence with the NOCACHE clause:

CREATE SEQUENCE dts_route_seq NOCACHE;

Note that there is a performance hit because Oracle now has to "commit" each time you increment the sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM