Postgres 函数创建 - 错误:没有指定语言 SQL 状态:42P13

问题描述 投票:0回答:3

我是函数新手。我正在尝试通过以下链接创建一个函数 -

http://www.postgresqltutorial.com/creating-first-trigger-postgresql/
。但它给出了一些错误。下面给出了代码块和错误。

代码块:

CREATE OR REPLACE FUNCTION log_last_name_changes()
  RETURNS trigger AS
$BODY$
BEGIN
 IF NEW.last_name <> OLD.last_name THEN
 INSERT INTO employee_audits(employee_id,last_name,changed_on)
 VALUES(OLD.id,OLD.last_name,now());
 END IF;
 
 RETURN NEW;
END;
$BODY$

错误:

错误:未指定语言
SQL状态:42P13

接下来我可以尝试什么?

sql database postgresql triggers dbfunctions
3个回答
30
投票

试试这个方法:

CREATE OR REPLACE FUNCTION log_last_name_changes()
RETURNS trigger AS
$BODY$
BEGIN
IF NEW.last_name <> OLD.last_name THEN
INSERT INTO employee_audits(employee_id,last_name,changed_on)
VALUES(OLD.id,OLD.last_name,now());
END IF;

RETURN NEW;
END;
$BODY$

LANGUAGE plpgsql VOLATILE -- Says the function is implemented in the plpgsql language; VOLATILE says the function has side effects.
COST 100; -- Estimated execution cost of the function.

0
投票

如果到达这里是因为你的

function
给了你同样的错误(就像我的一样)..这是一个过度烘焙的示例,使用函数将右下角“blurb”上的推文更新为“hello world”。

重要提示:语言位于最后一个分号之前(见下文)。这在已接受的解决方案中很容易被忽略。

id(序列号) pub_id(文本) 推文(文本)
1 abc 世界你好
2 定义 宣传
-- Optional drop if replace fails below.
drop function if exists sync_tweets(text, text);

create or replace function sync_tweets(
    src_pub_id text, -- function arguments
    dst_pub_id text
) returns setof tweets as -- i.e. rows. int, text work too
$$
declare
    src_id    int; -- temp function variables (not args)
    dest_id   int;
    src_tweet text;
begin
    -- query result into a temp variable
    src_id := (select id from tweets where pub_id = src_pub_id);

    -- query result into a temp variable (another way)
    select tweet into src_tweet from tweets where id = src_id;

    dest_id := (select id from tweets where pub_id = dst_pub_id);
    update tweets set tweet=src_tweet where id = dest_id;

    return query -- i.e. rows, return 0 with return int above works too
        select * from tweets where pub_id in (src_pub_id, dst_pub_id);
end
$$ language plpgsql; -- need the language to avoid ERROR 42P13

-- Run it!
select * from sync_tweets('abc', 'def');

/*
  Outputs
   __________________________________________________ 
  |  id (serial)  |  pub_id (text)  |  tweet (text)  |
  |---------------|-----------------|----------------|
  |  1            |  abc            |  hello world   |
  |  2            |  def            |  blurb         |
  --------------------------------------------------
*/

0
投票

我在下面遇到了同样的错误:

错误:未指定语言

当我创建PL/pgSQL函数时,如下所示:

CREATE FUNCTION my_func() RETURNS INTEGER AS $$
BEGIN
RETURN 2;
END;
$$;

于是,我如下图设置

LANGUAGE plpgsql
,然后错误就解决了:

CREATE FUNCTION my_func() RETURNS INTEGER AS $$
BEGIN
RETURN 2;
END; -- ↓ Here ↓
$$ LANGUAGE plpgsql;

或者:

CREATE FUNCTION my_func() RETURNS INTEGER LANGUAGE plpgsql AS $$
BEGIN                                    -- ↑ ↑ Here ↑ ↑
RETURN 2;
END;
$$;
© www.soinside.com 2019 - 2024. All rights reserved.