Question: I want to test an if statement in PostgreSQL:
IF (SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql') > 0 THEN
PRINT 'Good'
ELSE
PRINT 'Bad'
END IF;
Now this throws an error at IF.
As far as I have read, this is because I need to use plpgsql to be able to use if, print, and variables.
So far, I probably also have to use SELECT instead of print as well.
How can I switch the language before executing this statement to plpgsql ?
I want to test it first, BEFORE I put it in a stored procedure. To test code with variables etc.
Edit:
Solved by:
DO LANGUAGE plpgsql $$
BEGIN
IF (SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql') > 0 THEN
RAISE NOTICE 'GOOD';
ELSE
RAISE NOTICE 'BAD';
END IF;
END;
$$;
PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part.
“lang_name” is simply the name of the procedural language. If the language is not mentioned, PostgreSQL will use the default procedural language, PL/pgSQL. $$ (double quoting) is a PostgreSQL substitute for single quotes to avoid quoting issues inside the BEGIN block.
The not-null constraint in PostgreSQL ensures that a column can not contain any null value. This is a column constraint. No name can be defined to create a not-null constraint. This constraint is placed immediately after the data-type of a column.
Syntax: IF boolean-expression THEN statements [ ELSIF boolean-expression THEN statements [ ELSIF boolean-expression THEN statements ...]] [ ELSE statements ] END IF; IF-THEN-ELSE statements add to IF-THEN by letting you specify an alternative set of statements that should be executed if the condition is not true.
If you just want to test code snippets without going through all the hassle of building and dropping a function, then you can use DO
:
=> do language plpgsql $$
begin
-- Yes, I have a table called pancakes in my playpen database.
if (select count(*) from pancakes) > 0 then
raise notice 'Got some';
else
raise notice 'Got none';
end if;
end;
$$;
You'll need 9.0+ to use DO
.
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