Postgresql string concatenation: error: syntax error at or near "msg"

I am trying to raise an issue in a Postgresql function using a concatenated message, but I get an error message at runtime:

error: syntax error at or near "msg"

The code is the following:

CREATE OR REPLACE FUNCTION insertUserAccount(
    id             bigint,
    nname          varchar(40),
    email          varchar(40),
    pwd            varchar,
    status         smallint,
    last_update  bigint,
    preferences    json,
    bits           integer,
    adm            json)
    RETURNS bigint AS $$
DECLARE
    rowc INTEGER;
    ret_id bigint;
    msg text;
BEGIN
    ...
    IF ( rowc > 0 ) THEN
        msg = 'User account already exists or name or email is unavailable (id=' || id
            || ', name=' || nname
            || ', email=' || email || ')';
        RAISE EXCEPTION msg USING ERRCODE = '23505';
    ELSE
    ...

Upvotes: 1

Views: 1654

Answers (2)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 658082

The actual problem is the faulty syntax for RAISE EXCEPTION. I would simplify overall:

IF rowc > 0 THEN
   RAISE EXCEPTION 'User account already exists or name or email is unavailable (id=%,name=%,email=%)'
                 , id, nname, email  USING ERRCODE = '23505';
ELSE ...

The variable msg might not be needed at all then. It is generally best to keep the number of assignments low, since those are rather expensive in PL/pgSQL (as compared to other programming languages). Not dramatic, but still ..

Upvotes: 3

Milen A. Radev
Milen A. Radev

Reputation: 62623

Use := for assignment in PL/pgSQL

Upvotes: 1

Related Questions