我在PostgreSQL 9.5中有以下UPSERT:
INSERT INTO chats ("user", "contact", "name")
VALUES ($1, $2, $3),
($2, $1, NULL)
ON CONFLICT("user", "contact") DO NOTHING
RETURNING id;
Run Code Online (Sandbox Code Playgroud)
如果没有冲突,则返回如下内容:
----------
| id |
----------
1 | 50 |
----------
2 | 51 |
----------
Run Code Online (Sandbox Code Playgroud)
但如果存在冲突,则不会返回任何行:
----------
| id |
----------
Run Code Online (Sandbox Code Playgroud)
id如果没有冲突,我想返回新列,或者返回id冲突列的现有列.
可以这样做吗?如果是这样,怎么样?
我正在PL/pgSQL中编写一个函数,我正在寻找检查行是否存在的最简单方法.
现在我正在选择一个integer进入a boolean,这不起作用.我对PL/pgSQL还没有足够的经验知道最好的方法.
这是我的功能的一部分:
DECLARE person_exists boolean;
BEGIN
person_exists := FALSE;
SELECT "person_id" INTO person_exists
FROM "people" p
WHERE p.person_id = my_person_id
LIMIT 1;
IF person_exists THEN
-- Do something
END IF;
END; $$ LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)
更新 - 我现在正在做这样的事情:
DECLARE person_exists integer;
BEGIN
person_exists := 0;
SELECT count("person_id") INTO person_exists
FROM "people" p
WHERE p.person_id = my_person_id
LIMIT 1;
IF person_exists < 1 THEN
-- Do something
END IF;
Run Code Online (Sandbox Code Playgroud) 我写了一个函数为一个简单的博客引擎创建帖子:
CREATE FUNCTION CreatePost(VARCHAR, TEXT, VARCHAR[])
RETURNS INTEGER AS $$
DECLARE
InsertedPostId INTEGER;
TagName VARCHAR;
BEGIN
INSERT INTO Posts (Title, Body)
VALUES ($1, $2)
RETURNING Id INTO InsertedPostId;
FOREACH TagName IN ARRAY $3 LOOP
DECLARE
InsertedTagId INTEGER;
BEGIN
-- I am concerned about this part.
BEGIN
INSERT INTO Tags (Name)
VALUES (TagName)
RETURNING Id INTO InsertedTagId;
EXCEPTION WHEN UNIQUE_VIOLATION THEN
SELECT INTO InsertedTagId Id
FROM Tags
WHERE Name = TagName
FETCH FIRST ROW ONLY;
END;
INSERT INTO Taggings (PostId, TagId) …Run Code Online (Sandbox Code Playgroud) 在 Postgres 12 数据库中,我在一个函数中有多个查询(SELECT、UPDATE、 ...),总共需要大约 20 分钟才能完成。我在顶部有一个检查,它执行UPDATEifstatus未运行:
create or replace function aaa.fnc_work() returns varchar as
$body$
begin
if (select count(*) from aaa.monitor where id='invoicing' and status='running')=0 then
return 'running';
else
update aaa.monitor set status='running' where id='invoicing';
end if;
--- rest of code ---
--finally
update aaa.monitor set status='idle' where id='invoicing';
return '';
exception when others then
return SQLERRM::varchar;
end
$body$
language plpgsql;
Run Code Online (Sandbox Code Playgroud)
这个想法是为了防止其他用户执行直到--- rest of code ---空闲status。
然而,其他人(调用相同的函数)似乎看不到更新的状态,他们也继续并开始执行 …
postgresql stored-procedures transactions plpgsql task-queue
postgresql ×4
plpgsql ×3
sql ×3
upsert ×2
concurrency ×1
exists ×1
task-queue ×1
transactions ×1