我正在尝试在postgreSQL中执行此操作: 您不能存储超过5条记录(行)。
CREATE FUNCTION contar_dest()
RETURNS TRIGGER AS
$body$
BEGIN
IF (SELECT COUNT(ID) FROM "LUGARES" WHERE demanda is not null) > 5
THEN
DELETE FROM "LUGARES"
WHERE ID = (SELECT max(ID) FROM "LUGARES");
RETURN NULL;
END IF;
END;
$body$
LANGUAGE plpgsql;
CREATE TRIGGER contar
AFTER INSERT
ON "LUGARES"
FOR EACH ROW
EXECUTE PROCEDURE contar_dest();
当我尝试插入一行时,请告诉我:
错误:执行到达触发程序结束而未找到RETURN 语境:PL / pgSQL函数contar_dest()
现在我按照自己的意愿行事,但错误就是这样:
CREATE FUNCTION contar_dest()
RETURNS TRIGGER AS
$body$
BEGIN
IF ((SELECT COUNT(ID) FROM "LUGARES" WHERE demanda is not null) > 5) THEN
DELETE FROM "LUGARES"
WHERE ID = (SELECT NEW.ID FROM "LUGARES");
ELSIF ((SELECT COUNT(ID) FROM "LUGARES" WHERE demanda is not null) < 5) THEN
RETURN NULL;
END IF;
RETURN NULL;
END;
$body$
LANGUAGE plpgsql;
CREATE TRIGGER contar
AFTER INSERT
ON "LUGARES"
FOR EACH ROW
EXECUTE PROCEDURE contar_dest();
INSERT INTO "LUGARES"(
nombre, demanda)
VALUES ('Valencia',2000);
ERROR: a subquery used as an expression returned more than one record
CONTEXT : SQL statement : " DELETE FROM "LUGARES"
WHERE ID = ( SELECT FROM NEW.ID "LUGARES") »
PL / pgSQL contar_dest ( ) function in line 4 SQL statement
********** Error **********
答案 0 :(得分:0)
错误是由您使用最多需要1行的语法引起的,但是在执行时会返回多行。
变化:
DELETE FROM "LUGARES"
WHERE ID = (SELECT NEW.ID FROM "LUGARES");
要:
DELETE FROM "LUGARES"
WHERE ID IN (SELECT NEW.ID FROM "LUGARES");
=
仅适用于1个值,但IN
允许使用多个值。