I have an anonymous DO
block in a Postgres database like below:
DO LANGUAGE plpgsql $$
DECLARE
FUNC_ID smallint;
BEGIN
SELECT COUNT(1) INTO FUNC_ID FROM FUNCTION WHERE NAME = 'addition';
IF FUNC_ID = 0 THEN
INSERT INTO FUNCTION ( ID, NAME, DESCRIPTION, FUNCTION)
values ((select (max(id)+1) from FUNCTION), 'subtraction'
, 'calculate', 'catalog');
END IF;
END;
$$;
If execute this block of code it gives output as only DO
.
How to output the whole block of code to console?
Execute a PL/SQL anonymous block using SQL*Plus. Once you have the code of an anonymous block, you can execute it using SQL*Plus, which is a command-line interface for executing SQL statement and PL/SQL blocks provided by Oracle Database.
Label: This is an optional keyword used to identify the anonymous block, in case of an EXIT statement or if we need to qualify the variables names that are declared in the block. The label given before DECLARE/BEGIN should match with the level given after the END keyword. Functions and procedures are defined in the BEGIN section of a block.
PostgreSQL started supporting anonymous blocks with version 9.0. Here “code” can be considered as the body of a function with no parameters, which is going to return void and be parsed and executed one time only (i.e., not going to be stored in database catalog).
A block without a name is an anonymous block. An anonymous block is not saved in the Oracle Database server, so it is just for one-time use. However, PL/SQL anonymous blocks can be useful for testing purposes.
Use a RAISE NOTICE statement
postgres=# DO $$BEGIN RAISE NOTICE 'Hello %', SESSION_USER; END; $$;
NOTICE: Hello pavel
DO
See more in related documentation.
Your code is twisted in multiple ways. Use instead:
DO
$do$
BEGIN
IF EXISTS (SELECT 1 FROM function WHERE name = 'addition') THEN
INSERT INTO function(id, name, description, function)
SELECT max(id) + 1, 'subtraction', 'calculate', 'catalog'
FROM function;
RAISE NOTICE 'Whatever'; -- see Pavel's answer
END IF;
END
$do$;
You probably should have a serial
primary key, drawing the next value from a SEQUENCE
. What you have is prone to race conditions and a typical anti-pattern.
Also I wouldn't use function
as identifier even if that's allowed in Postgres. It's a reserved word in the SQL standard.
CREATE TABLE func
func_id serial PRIMARY KEY
, func text NOT NULL
, description text
, find_proper_name text)
);
Then your whole statement can be:
INSERT INTO func(func, description, find_proper_name)
SELECT 'subtraction', 'calculate', 'catalog'
WHERE EXISTS (SELECT 1 FROM func WHERE func = 'addition');
You don't need a DO
statement at all here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With