无法返回手动生成的ID

时间:2017-12-04 15:21:14

标签: oracle plsql oracle11g

我试图返回new_id的值,但没有成功。有什么帮助吗?

create or replace FUNCTION create_election (name        VARCHAR, 
                             description VARCHAR, 
                           type          VARCHAR, 
                           subtype       VARCHAR, 
                           started_at    VARCHAR, 
                           ended_at      VARCHAR) 
RETURN INT
IS
v_id int;
BEGIN
    INSERT INTO election VALUES  ( 
          (  SELECT nvl(max(id)+1, 0) AS new_id FROM  election ) , 
          name,  description,  type, subtype, started_at, ended_at, 
          0,  0,  0 
) RETURNING new_id into v_id ;
END;

---更新--- 我根据最佳实践选择解决方案。谢谢你的帮助。

4 个答案:

答案 0 :(得分:1)

使用SELECT nvl(max(id)+1, 0) AS new_id FROM election之类的查询生成ID是一种不好的做法。每当两个或更多用户调用此函数时,您将获得重复值。

Oracle有这样的序列。序列始终生成唯一值。首先,创建序列:

create sequence election_seq;

然后在你的函数中使用它:

create or replace FUNCTION create_election (name        VARCHAR, 
                             description VARCHAR, 
                           type          VARCHAR, 
                           subtype       VARCHAR, 
                           started_at    VARCHAR, 
                           ended_at      VARCHAR) 
RETURN INT
IS
v_id int;
BEGIN
  v_id := election_seq.nextval;
  INSERT INTO election VALUES  
  (v_id, name,  description,  type, subtype, started_at, ended_at, 0,  0,  0);
END;

答案 1 :(得分:1)

您需要在插入之前添加select into

  SELECT nvl(max(id)+1, 0) into v_id  FROM  election

稍后在插入和返回时使用v_id

答案 2 :(得分:0)

我认为在结束函数的END之前需要这一行:

RETURN v_id;

您正在将数据输入到局部变量v_id中,但不会从函数中返回它。

答案 3 :(得分:0)

create or replace FUNCTION create_election (name        VARCHAR, 
                             description VARCHAR, 
                           type          VARCHAR, 
                           subtype       VARCHAR, 
                           started_at    VARCHAR, 
                           ended_at      VARCHAR) 
RETURN INT
IS
  v_id int;
  new_id int;
BEGIN
    INSERT INTO election VALUES  ( 
          nvl(  (SELECT max(id)+1 AS new_id FROM  election) ,1 ), 
          name,  description,  type, subtype, started_at, ended_at, 
          0,  0,  0  
) RETURNING new_id into v_id ;

  return v_id;
END;