我有一个查询,添加后会返回其ID
DO
$do$
BEGIN
IF (SELECT COUNT(*) = 0 FROM COMMENTS WHERE PARENT_ID = ''${this.parent_id}') THEN
UPDATE COMMENTS SET HAS_CHILD = TRUE WHERE COMMENT_ID = '${this.parent_id}';
END IF;
INSERT INTO COMMENTS(USER_ID, ... , PARENT_ID, ... , HAS_CHILD) VALUES('${this.user_id}', ... , ${this.parent_id}, ... ', FALSE)
RETURNING COMMENT_ID;
END
$do$
执行请求时,发生错误:ERROR: query has no destination for result data
CONTEXT: PL/pgSQL function inline_code_block line 3 at SQL statement
SQL state: 42601
。没有RETURNING COMMENT_ID;
的请求成功。
为什么不使用RETURNING COMMENT_ID;
执行请求?
答案 0 :(得分:1)
在PL / pgSQL中,必须使用关键字INTO
将返回值分配给变量,请参见:
https://www.postgresql.org/docs/9.4/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW
DO
$do$
DECLARE
result INTEGER := 0;
BEGIN
IF (SELECT COUNT(*) = 0 FROM COMMENTS WHERE PARENT_ID = '${this.parent_id}') THEN
UPDATE COMMENTS SET HAS_CHILD = TRUE WHERE COMMENT_ID = '${this.parent_id}';
-- Here you could specify returning value for the UPDATE branch...
END IF;
INSERT INTO COMMENTS(USER_ID, ... , PARENT_ID, ... , HAS_CHILD) VALUES('${this.user_id}', ... , ${this.parent_id}, ... ', FALSE)
RETURNING COMMENT_ID INTO result;
RETURN result;
END
$do$
或者您可以使用RETURN QUERY
语法:
DO
$do$
BEGIN
IF (SELECT COUNT(*) = 0 FROM COMMENTS WHERE PARENT_ID = '${this.parent_id}') THEN
UPDATE COMMENTS SET HAS_CHILD = TRUE WHERE COMMENT_ID = '${this.parent_id}';
-- Here you could specify returning value for the UPDATE branch...
END IF;
RETURN QUERY
INSERT INTO COMMENTS(USER_ID, ... , PARENT_ID, ... , HAS_CHILD) VALUES('${this.user_id}', ... , ${this.parent_id}, ... ', FALSE)
RETURNING COMMENT_ID;
END
$do$