简体   繁体   English

选择表中没有行的列的最大值

[英]select max value of a column in table with no rows

I am using oracle database我正在使用 oracle 数据库

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.在表中插入一行时,我需要找到一列的最大值并将其递增 1,然后在要插入的行中使用该值。

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.但是当它们在表中没有条目时返回 null。

How can i get default value of 1 when their are no entries in table.当它们在表中没有条目时,我如何获得默认值 1。

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.您可以使用 Oracle 序列来实现此目标。

As for the null, you can use NVL to give a default value (say, 0) in case the function returns null.至于 null,您可以使用NVL给出默认值(例如 0),以防函数返回 null。

Use sequence for the ID.使用序列作为 ID。 You need to create sequence.您需要创建序列。 See below link见下面的链接

http://www.basis.com/onlinedocs/documentation/b3odbc/sql_sequences.htm 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为 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尽管如果您不介意路线 ID 中的奇怪间隙,使用序列可能会更容易

select 0 when null, then it will be 0+1 which is a correct number compared to null+1当 null 时选择 0,那么它将是 0+1,与 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:如果您担心路由 ID 中存在间隙,请使用 NOCACHE 子句创建序列:

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.请注意,这会影响性能,因为 Oracle 现在必须在每次递增序列时“提交”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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