【问题标题】:Increment an attribute in postgresql function在 postgresql 函数中增加一个属性
【发布时间】:2017-03-29 16:04:08
【问题描述】:

下面是我在表中插入值的函数.. 但是我希望 numofexisting 属性是一个不断增加的数字以便唯一.. 我怎样才能实现它?

 CREATE OR REPLACE FUNCTION insert_CourseRun()
    RETURNS VOID AS
    $$
    DECLARE curr_sem integer;
    DECLARE curr_season semester_season_type;
    DECLARE curr_year smallint ;
    DECLARE numofexisting integer;
    BEGIN
        numofexisting := (SELECT COUNT(*) FROM public."courserun") + 1 ;
        curr_sem := (SELECT s.semester_id FROM "semester" as s WHERE s.semester_status = 'present');
        if (curr_sem % 2 = 0) then 
            curr_season = 'spring';
            curr_year = curr_sem /2;
        else
            curr_season = 'winter';
            curr_year = (curr_sem+1) /2;
        end if;

        INSERT INTO public."courserun"  
        SELECT c.course_code, numofexisting, 5, 5, 2, curr_sem, labcode_for_course(c.course_code)
        FROM "Course" as c
        WHERE c.typical_season= curr_season and c.typical_year = curr_year;
    END;
    $$
    LANGUAGE 'plpgsql' VOLATILE;

【问题讨论】:

  • 在表定义中声明为serial
  • @GordonLinoff 这是唯一的方法吗?
  • 不,但最简单和最好的。或者明确地使用一个序列。
  • @LaurenzAlbe 明确的顺序是什么?我不能使用这种方式,因为我已经建立了我的数据库并且我想要串行的属性是主键..
  • 我添加了一个答案,其中包含如何使用序列的说明。

标签: database postgresql function datatables


【解决方案1】:

创建一个序列:

/* instead of 42, use a value larger than the current maximim value */
CREATE SEQUENCE courserun_seq START 42;

然后像这样插入:

INSERT INTO courserun (..., numofexisting, ...)
   VALUES (..., nextval('courserun_seq'), ...);

这将假设 所有 插入到表中都是这样完成的。

您还可以更改表格以自动使用默认值:

ALTER TABLE courserun
   ALTER numofexisting SET DEFAULT nextval('courserun_seq');

然后您可以省略 INSERT 列列表中的列或使用值 DEFAULT,如下所示:

INSERT INTO courserun (..., numofexisting, ...)
   VALUES (..., DEFAULT, ...);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多