5

I'm trying to get a PSQL script running using variables in an example like the one below without declaring functions and having to call them.

DECLARE
    result TEXT;
BEGIN
    SELECT INTO result name 
FROM test;

    RAISE NOTICE result;
END;

Where table test only has 1 row and column. Is this possible without having to wrap this script inside a function. This will allow me to call the script via say command line easier.

Thanks guys.

1 Answer 1

14

You can use DO to create and execute an anonymous function:

DO executes an anonymous code block, or in other words a transient anonymous function in a procedural language.

Something like this:

do $$
    declare result text;
    begin
        select name into result from test;
        raise notice '%', result;
    end;
$$;

I also fixed your raise notice.

If you just want to dump the single value from the table to the standard output in a minimal format (i.e. easy to parse), then perhaps --tuples-only will help:

-t
--tuples-only
Turn off printing of column names and result row count footers, etc. This is equivalent to the \t command.

So you could say things like this from the shell:

result=$(echo 'select name from test;' | psql -t ...)
Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting the following: ERROR: syntax error at or near "do" LINE 1: do $$... we're using PostreSQL v8.3. Would there be an equivalent for that version?
@mlevit: DO is a version 9 addition. I'm not aware of anything like it in 8.3 and I doubt there is any alternative than a named function. What exactly are you trying to do? Can you provide a bit more context?
what we're basically doing is trying to create dynamic scripts to perform some data manipulation (via command line execution). The reason why we don't want to use functions is because they must be created in the DB every time before they can be run.
@mlevit: You might be able to get away with psql -t as in my update.
Version 8.3 will be five years old in February 2013, at which point it will hit end of life. If you need features of more recent releases, you might not want to wait for that to upgrade. (The upgrade may be less pain than working around lack of this one new feature.) I would suggest skipping 8.4 and 9.0 and going to 9.1, or maybe even jumping onto 9.2 when it is released next month.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.