I am attempting to write a function in PostgreSQL 9.0. This will eventually be used in a new aggregate function, but one step at a time. Here is what I have so far:
create or replace function encstate(text,text) returns text as $$
DECLARE
oldstate alias for $1;
arg alias for $2;
BEGIN
IF length(oldstate)>0 then
select 'Encrypted';
else if
select '';
end if;
END;
$$ language sql strict immutable;
(I know I'm not yet using the $2 argument.)
The result is:
ERROR: syntax error at or near "alias"
LINE 3: oldstate alias for $1;
When I remove the DECLARE
block and just refer to the arguments as $1 etc in the body, the result is:
ERROR: syntax error at or near "if"
LINE 3: if length($1)>0 then
As far as I can tell, what I have matches examples found on the web, except I could find no examples of functions with an if-statement, so I have no idea what I'm doing wrong. Any help would be appreciated.
If you want a SQL function:
create or replace function encstate(text, text) returns text as $$
select case
when length($1) > 0 then 'Encrypted'
else ''
end
;
$$ language sql strict immutable;
SQL has no variables or control structures as it is not procedural, it is declarative. If you want procedural features then use a plpgsql function:
create or replace function encstate(text, text) returns text as $$
DECLARE
oldstate alias for $1;
arg alias for $2;
BEGIN
IF length(oldstate) > 0 then
return 'Encrypted';
else
return '';
end if;
END;
$$ language plpgsql strict immutable;