【问题标题】:How can I run an ad-hoc script in PostgreSQL?如何在 PostgreSQL 中运行临时脚本?
【发布时间】:2013-09-16 12:31:30
【问题描述】:

我正在尝试在 PostgreSQL 9.2 中运行它:

RAISE NOTICE 'hello, world!';

服务器说:

Error : ERROR:  syntax error at or near "RAISE"
LINE 1: RAISE NOTICE 'hello, world!'
        ^

为什么?

【问题讨论】:

    标签: postgresql postgresql-9.2


    【解决方案1】:

    使用匿名code block

    DO language plpgsql $$
    BEGIN
      RAISE NOTICE 'hello, world!';
    END
    $$;
    

    Variables are referenced 使用%

    RAISE NOTICE '%', variable_name;
    

    【讨论】:

    • 这正是我需要的:)
    • 为了让它更短,你可以删除换行符和 language plpgsql
    • @ruut 在我使用的 pg 9.6 版本中,我经常在尝试创建忘记指定语言的函数时出错ERROR: no language specified 也许它以前是默认值?
    【解决方案2】:

    raise 仅是 PL/pgSQL

    http://www.postgresql.org/docs/current/static/plpgsql-errors-and-messages.html

    create or replace function r(error_message text) returns void as $$
    begin
        raise notice '%', error_message;
    end;
    $$ language plpgsql;
    
    select r('an error message');
    NOTICE:  an error message
    

    【讨论】:

      【解决方案3】:

      简单示例:

      CREATE OR REPLACE FUNCTION test()     
      RETURNS TRIGGER AS
      '
      DECLARE
      
      
      num int;
      
       BEGIN
      IF TG_OP = ''INSERT'' THEN
      select count(*) into num from test_table;
      IF num >= 1 THEN
      RAISE WARNING ''Cannot Insert more than one row'';
      RETURN OLD;
      END IF;
      ELSE
      RETURN NEW;
      END IF;
      
      END;
      ' LANGUAGE plpgsql;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        相关资源
        最近更新 更多