Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error when declaring a postgres variable [duplicate]

I'm getting a SQL error when trying to declare a variable in Postgresql. Check out my code below:

declare number int8;

begin
 select ID into number from public.People p where p."Name" = 'Jeff';
 if found then
   insert into public.Friends ("PeopleID", "Name", "PhoneNumber")
   values (number, 'Jeff', '205-123-4567')
 end if;
end;

When I try and run this, it returns this exception:

SQL Error [42601]: ERROR: syntax error at or near "int8"

I'm expecting there to be only one entry with the name "Jeff", so I won't have to worry about having more than one possible value for "number".

like image 618
Colby Willoughby Avatar asked Jan 21 '26 09:01

Colby Willoughby


1 Answers

You cannot declare a variable in pure SQL in Postgres, unlike other RDBMS such as SQL Server or MySQL.

Your code compiles properly in this Postgres 12 db fiddle when I put it within plgpsql procedure (still, you should consider another name that number for a variable).

create procedure test_proc() language plpgsql AS '
declare number int8;
begin
    select ID into number from people p where p."Name" = ''Jeff'';
    if found then
        insert into friends ("PeopleID", "Name", "PhoneNumber")
            values (number, ''Jeff'', ''205-123-4567'');
    end if;
end;
';

Or in Postgres < 11 with a void function:

create function test_proc() returns void language plpgsql AS '
declare number int8;
begin
    select ID into number from people p where p."Name" = ''Jeff'';
    if found then
        insert into friends ("PeopleID", "Name", "PhoneNumber")
            values (number, ''Jeff'', ''205-123-4567'');
    end if;
end;
';

You might also want consider this insert ... select query, that achieves the same purpose in a single database call:

insert into friends("PeopleID", "Name", "PhoneNumber")
select ID, "Name", '205-123-4567' from people where p."Name" = 'Jeff'
like image 154
GMB Avatar answered Jan 23 '26 00:01

GMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!