我正在為某些操作撰寫 1 個 PostgreSQL 函式。為該函式撰寫 SQL 遷移但由于 liquibase 無法識別某些部分而面臨格式錯誤。
功能 Liquibase 遷移:
CREATE OR REPLACE FUNCTION schema.fncn(trId integer, sts integer, stIds character varying)
RETURNS double precision
LANGUAGE plpgsql
AS '
DECLARE
abc integer;
query CHAR(1500);
xyz integer;
BEGIN
query := ''select sum(t.a)
FROM schema.tbl t
where t.id in(1,2)
and t.status ='' || sts ||
'' and t.status <> 2
and t.tr_id ='' || trId ||
'' and t.sw in('''', ''N'')'';
IF stIds is not null then
query := query || '' AND t.st_id IN ('' || stIds || '')'';
ELSE
END IF;
EXECUTE query INTO abc;
SELECT abc INTO xyz;
RETURN xyz;
END;
'
;
以下錯誤它拋出:
引起:org.postgresql.util.PSQLException:錯誤:“N”或附近的語法錯誤
原因:liquibase.exception.DatabaseException:錯誤:“N”處或附近的語法錯誤
任何建議我錯過了什么?
uj5u.com熱心網友回復:
'直接的問題是單引號的嵌套。為了更容易,對函式體使用美元報價。您可以通過選擇不同的分隔符來嵌套美元參考的字串。
為避免引數連接出現任何問題,請在查詢中使用引數占位符USING并使用子句傳遞值。然而,這將需要兩個不同的execute呼叫。
我假設stIds是逗號分隔的值字串。要將其用作(單個)占位符,請使用string_to_array()- 或更好的方法將其轉換為陣列:將輸入引數的型別更改為text[]并直接傳遞陣列。
查詢變數最好定義為text,不要使用 char。也無需將查詢結果復制到不同的變數中(順便說一句,使用xyz := abc;而不是 a會更有效select into)
CREATE OR REPLACE FUNCTION schema.fncn(trId integer, sts integer, stIds character varying)
RETURNS double precision
LANGUAGE plpgsql
AS
$body$
DECLARE
abc integer;
query text;
BEGIN
query := $q$ select sum(t.a)
FROM schema.tbl t
where t.id in (1,2)
and t.status = $1
and t.status <> 2
and t.tr_id = $2
and t.sw in ('''', 'N') $q$;
IF stIds is not null then
query := query || $sql$ AND t.st_id = ANY (string_to_array($4, ',') $sql$;
EXECUTE query INTO abc
using trid, sts, stids;
ELSE
EXECUTE query INTO abc
using trid, sts;
END IF;
RETURN abc;
END;
$body$
;
請注意,在 Liquibase 更改中,您必須使用splitStatements=false它才能在沒有錯誤的情況下運行它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/467474.html
標籤:PostgreSQL 弹簧靴 液基 liquibase-sql
