yegor256
yegor256

Reputation: 105063

How can I run an ad-hoc script in PostgreSQL?

I'm trying to run this in PostgreSQL 9.2:

RAISE NOTICE 'Hello, World!';

And the server says:

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

Why?

Upvotes: 44

Views: 73895

Answers (3)

Mehdi Sadighian
Mehdi Sadighian

Reputation: 118

A simple example:

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;

Upvotes: 0

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125244

raise is PL/pgSQL only.

See 43.9. Errors and Messages.

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

Upvotes: 25

Tomas Greif
Tomas Greif

Reputation: 22643

Use an anonymous code block:

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

Variables are referenced using %:

RAISE NOTICE '%', variable_name;

Upvotes: 88

Related Questions