【发布时间】: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