gpt4 book ai didi

sql - 将 MAX(id) 分配给序列

转载 作者:行者123 更新时间:2023-12-02 07:39:32 25 4
gpt4 key购买 nike

我想使用 powerbuilder 中的一些数据向表中插入一些数据。在使用 SQL 序列递增最后一个已知 ID 时,我有点迷茫。

我知道如何找到最大 ID,但我如何使用序列来确保每个新的 INSERT 都会将 ID 递增 1?

到目前为止,我所知道的就是如何找到我的最大 ID:

SELECT MAX(id)
FROM table_name;

编辑我正在为我的数据库使用 Oracle

谢谢。

最佳答案

如果要向其中插入数据的表的 ID 值来自模式序列中已经存在的值,那么欢迎您继续使用该序列来插入新记录。

如果你想创建一个新的序列,从表的 ID 列的最大值开始生成数字,那么你可以执行以下操作

创建序列:

create sequence Seq_Name;

更改值序列将开始于

declare
l_max_ID number;
l_Temp_val number;
begin
select max(ID) into l_max_ID
from your_table;

execute immediate 'alter sequence Seq_Name increment by ' || To_Char(l_Max_ID);

select Seq_Name.currval into l_temp_val
from dual;

execute immediate 'alter sequence Seq_Name increment by ' || To_Char(1);
end;

并使用下面列出的任何方法来获取序列的下一个值。

Insert into your_table(id, [other_columns])
values(Seq_name.nextval, [other_values]);

create or replace trigger Tr_Name before insert on Your_Table_name
for each row
begin
-- if you are using oracle prior to 11g then
select Seq_name.nextval into :new.id -- or any other column
from dual;
-- OR
-- if your Oracle version is 11g onward you can simply assign
-- sequence's value to a new ID
:new.id := Seq_Name.nextval;

end;

关于sql - 将 MAX(id) 分配给序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12566201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com