任何人都可以协助 postgresql 中函数的语法(来自 mysql)
我试图在 PostgreSQL 中创建以下函数,但出现以下错误。这是来自我需要转换为 PostgreSQL 的 MySQL 过程。我无法将语法转换为 PostgreSQL。我是 PostgreSQL 的初学者。请帮助我。
CREATE OR REPLACE FUNCTION public.usp_failed_analyze4()
RETURNS TABLE(status varchar) as
$BODY$
SET @maxdate = (SELECT MAX(analyzetime) FROM wp_analyze_history);
SET @maxdateint = (SELECT DATEDIFF(NOW() ,MAX(analyzetime)) FROM wp_analyze_history);
SET @STATUS = SELECT Status from wp_analyze_history WHERE Status NOT IN ('OK','Table is already up to date','The Analyze task DID NOT run!') AND analyzetime = @maxdate);
SET @STATUSNOTRUN = 'The Analyze task DID NOT run!';
IF @maxdateint > 7
THEN SELECT @STATUSNOTRUN;
ELSE SELECT @STATUS as "";
$BODY$
LANGUAGE sql;
错误:错误:“@”处或附近的语法错误 位置:109
I am trying to create the following function in PostgreSQL but get the following error. This is from a MySQL procedure that I need to convert to PostgreSQL. I am failing to convert the syntax to PostgreSQL. I am a beginner in PostgreSQL. Please assist me.
CREATE OR REPLACE FUNCTION public.usp_failed_analyze4()
RETURNS TABLE(status varchar) as
$BODY$
SET @maxdate = (SELECT MAX(analyzetime) FROM wp_analyze_history);
SET @maxdateint = (SELECT DATEDIFF(NOW() ,MAX(analyzetime)) FROM wp_analyze_history);
SET @STATUS = SELECT Status from wp_analyze_history WHERE Status NOT IN ('OK','Table is already up to date','The Analyze task DID NOT run!') AND analyzetime = @maxdate);
SET @STATUSNOTRUN = 'The Analyze task DID NOT run!';
IF @maxdateint > 7
THEN SELECT @STATUSNOTRUN;
ELSE SELECT @STATUS as "";
$BODY$
LANGUAGE sql;
error: ERROR: syntax error at or near "@"
Position: 109
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您尝试 1:1 复制 MySQL 时,很难说出您想要什么。
但是,您的代码中存在几个问题:
语言sql
没有变量或IF语句。您需要使用 PL/pgSQL(语言 plpgsql
)declare
块来声明所有变量,实际代码需要一个begin ... end ;
也阻止。SET
来 分配select ... into ... from
@
在 SQL 中无效标识符,不能用于变量名(遵循 SQL 标识符的规则)。在 Postgres 中,一个常见的习惯是在变量前面加上一些前缀,以避免列名产生歧义。我使用l_
作为局部变量(但这完全是个人喜好)returns table
return
而不是select
将所有这些放在一起,它应该看起来像这样:
仍然有空间很多优化,但这尽可能匹配您的初始代码。
It's hard to tell what you want as you tried to copy the MySQL 1:1.
However, there are several problems in your code:
language sql
does not have variables or IF statements. You need to use PL/pgSQL (language plpgsql
)declare
block to declare all variables and the actual code needs abegin ... end;
block as well.SET
for assignmentselect ... into ... from
@
is invalid in an SQL identifier and can't be used for variable names (which follow the rules of SQL identifiers). In Postgres it's a common habit to prefix variable with something to avoid ambiguity with column names. I usel_
for local variables (but that's completely a personal preference)returns table
return
notselect
Putting that all together it should look something like this:
There is still room for a lot of optimization, but this matches your initial code as much as possible.