我正在制作一个SQL函数来执行智能插入并管理多对多表(由于一个值是变量,触发器将不起作用)。
这是示例的最低设置:
link_foo_to_bar (foo_id int, bar_id int)
foo (id serial, name character varying)
这是我的sql函数:
CREATE FUNCTION smart_insert (bar_id integer, foo_id integer, name character varying name)
RETURNS void AS $body$
INSERT INTO foo VALUES (foo_id, name);
INSERT INTO link_foo_to_bar (CURRVAL('foo_id_seq'), bar_id);
$body$ LANGUAGE sql;
现在的问题是,foo_id
是一serial
所以无论它得到DEFAULT
或INTEGER
作为传入值。该函数不接受DEFAULT
关键字。我应该如何更改函数以允许使用这种不同的参数?使用文字类型?
DEFAULT
在PostgreSQL中指定函数参数的方法如下:
CREATE FUNCTION smart_insert (
name character varying,
bar_id integer,
foo_id integer = -1
)
RETURNS void AS $body$
INSERT INTO foo VALUES (
CASE foo_id WHEN -1 THEN NEXTVAL('foo_id_seq') ELSE foo_id END,
name
);
INSERT INTO link_foo_to_bar (
CASE foo_id WHEN -1 THEN CURRVAL('foo_id_seq') ELSE foo_id END,
bar_id
);
$body$ LANGUAGE sql;
您可以通过以下方式调用它:
-- with an explicit foo_id:
smart_insert('abc', 1, 2);
-- applying the default value:
smart_insert('abc', 1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句