Declare variable set = select - postgresql

How do I declare a variable for used in a PostgreSQL 9.3 query?
CREATE or replace FUNCTION public.test()
returns int4
AS
$BODY$
DECLARE
cod_process bigint :=30001;
cod_instance bigint ;
utc_log timestamp without time zone := localtimestamp;
cod_log_type varchar(100) :='information ';
txt_log_text varchar(100):= 'start process';
txt_log varchar(100):= txt_log_text||'_'||cod_process;
set cod_instance= select max(cod_instance) as cod_instance from public.instance where public.instance.cod_process=cod_process;
BEGIN
INSERT INTO public.log (cod_process, cod_instance, utc_log,cod_log_type,txt_log)
VALUES (cod_process, cod_instance, utc_log,cod_log_type,txt_log );
RETURN 11;
END;
$BODY$ LANGUAGE 'plpgsql';
ERROR: type "cod_instance" does not exist
SQL state: 42704
Character: 383

Your demo function would work like this:
CREATE or replace FUNCTION public.test()
RETURNS int4 AS
$func$
DECLARE
_cod_process bigint := 30001;
_cod_instance bigint := (SELECT max(cod_instance)
FROM public.instance
WHERE cod_process = _cod_process);
_utc_log timestamp := localtimestamp;
_cod_log_type varchar(100) := 'information';
_txt_log_text varchar(100) := 'start process';
_txt_log varchar(100) := txt_log_text || '_' || cod_process;
BEGIN
INSERT INTO public.log
( cod_process, cod_instance, utc_log, cod_log_type, txt_log)
VALUES (_cod_process, _cod_instance, _utc_log, _cod_log_type, _txt_log);
RETURN 11;
END
$func$ LANGUAGE plpgsql;
Major points
You cannot use SET to assign a variable. That's taken to be the SQL command SET for setting run-time parameters.
But you can assign a variable at declaration time, even use a subquery for that.
UseLANGUAGE plpgsql, not LANGUAGE 'plpgsql'. It's an identifier.
#a_horse_with_no_name already wrote about naming conflicts.
Using a clean format goes a long way when debugging code ...
But you can probably simplify to:
CREATE OR REPLACE FUNCTION public.test(_cod_process bigint = 30001)
RETURNS integer AS
$func$
INSERT INTO public.log
(cod_process, cod_instance , utc_log, cod_log_type , txt_log)
SELECT $1, max(cod_instance), now() , 'information', 'start process_' || $1
FROM public.instance
WHERE cod_process = $1
GROUP BY cod_process
RETURNING 11
$func$ LANGUAGE sql;
Call:
SELECT public.test(); -- for default 30001
SELECT public.test(1234);
And depending on the actual data type of utc_log you probably want now() AT TIME ZONE 'UTC':
Ignoring timezones altogether in Rails and PostgreSQL

You need to run the select using the into clause inside the actual code block, not in the declare block:
begin
select max(cod_instance)
into cod_instance
from public.instance
where public.instance.cod_process=cod_process;
....
end;
It's usually not such a good idea to give variables (or parameters) the same name as columns in the table. There are certain cases where this can confuse the parser. To avoid any potential problems, try to use different names for your variables, e.g. by prefixing them (e.g. l_cod_process instead of cod_process or l_cod_instance instead of cod_instance)
More details on variable assignment can be found in the manual: http://www.postgresql.org/docs/current/static/plpgsql-statements.html

Related

Error while creating table : Syntax error at or near "#"

I am trying to convert SQL Server stored function to PostgreSQL stored function I am getting one syntactical error at declare #table1 table
CREATE OR REPLACE FUNCTION ETL_GetBuildingDetailsByUserID ( p_nInstID numeric=0)
RETURNS Boolean
AS $$
declare #table1 table
(
nbuilding numeric(18, 0) NOT NULL,
sbuild_name varchar(50) NULL,
sclient_build_id varchar(50) NULL,
nbuilding_inst_id numeric(18, 0) NOT NULL,
ntemp_building_id numeric(18,0) NULL,
nno_of_floors numeric(18,0) NULL
)
declare v_strDeptIds text;
v_strSubDeptIds text;
BEGIN
v_strsql := 'SELECT building.*
FROM building
WHERE (building.nbuilding_inst_id = '|| cast(p_nInstID as varchar(1)) ||')
';
print v_strsql
v_strsql1 text;
v_strsql1 := v_strsql
Insert into #table1; execute sp_executesql; v_strsql1
select * from #table1;
Return true;
END;
$$ LANGUAGE plpgsql;
Error
ERROR: syntax error at or near "#"
LINE 4: declare #table1 table
Can any one please tell what I am doing wrong?
It seems your function actually returns the result of a SELECT query, not a boolean value, so returns boolean is wrong to begin with.
To return a result, you need to declare the function as returns table(). But as you seem to simply return rows from the building table you can define it as returns setof building.
Then remove the useless dynamic SQL which seems completely unnecessary.
In PL/pgSQL there are no table variables, and copying the result of a query into one before returning that result from that table seems to be an unnecessary step which only slows down things. In Postgres you simply return the result of the query, there is no need to store it locally.
Additionally: rather than casting a parameter to another type inside the function it's better to declare that parameter with the type you expect.
So the simplified version of that function in PostgreSQL would be:
CREATE OR REPLACE FUNCTION ETL_GetBuildingDetailsByUserID ( p_nInstID text)
RETURNS setof building
AS $$
select building.*
from building
WHERE building.nbuilding_inst_id = p_nInstID
$$ LANGUAGE sql;
You can use it like this:
select *
from ETL_GetBuildingDetailsByUserID ('42');
Unrelated, but: using numeric(18,0) for columns that store values without decimals is overkill. You should define those columns as bigint. Much faster and uses less space than numeric.

specific column name on postgres function return

In postgres I have a custom function that will join first and last name.
CREATE FUNCTION full_name(u users) RETURNS varchar
LANGUAGE plpgsql VOLATILE
AS $$
BEGIN
RETURN CONCAT_WS(' ', u.first_name, u.last_name);
END;
$$;
It would be nice if I didn't have to set the the name of the column name and it was determined by the function eg.
eg. here I have to say the column name is full_name
SELECT
full_name(users) as full_name
But it would be nice if it atomically name it full_name
SELECT
full_name(users)
Is this possible to set in a custom function?
As the function parameter is the name of the table, you don't have to pass it.
You can call it like this:
select users.full_name
from users;
Note that you have to prefix the function name with the table name. You can also use an alias, but you still need the prefix.
select u.full_name
from users u;
In that case the column from the result set will be named full_name (the name of the function)
Btw: you don't need PL/pgSQL for the function. A plain SQL will likely be faster for this. Eespecially when you declare it stable instead of volatile - the it can be inlined and the overhead of calling the function is eliminated.
Try to use out parameter instead of returning the value:
CREATE FUNCTION full_name(in u users, out full_name varchar)
LANGUAGE plpgsql VOLATILE
AS $$
BEGIN
full_name := CONCAT_WS(' ', u.first_name, u.last_name);
END;
$$;
and
SELECT * FROM full_name(users)
This could be a solution to your problem. Instead of passing users as parameter you can use the first_name and last_name as parameters to the function.
CREATE OR REPLACE FUNCTION full_name(character varying ,character varying)
RETURNS character varying AS
$BODY$
declare
l_nom ALIAS FOR $1;
l_pnom ALIAS FOR $2;
begin
RETURN CONCAT_WS(' ', l_nom, l_pnom);
end;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION full_name(character varying ,character varying) OWNER TO postgres;
SELECT full_name(u.first_name, u.last_name)

Returning result set from Postgres functions

In my Postgres 9.2 database, I need to build a function that takes several parameters, performs several queries, and then returns a data set that is composed of several rows and several columns. I've built several test functions to get a better grasp of Postgres' functionality, here is one:
CREATE OR REPLACE FUNCTION sql_with_rows11(id integer) RETURNS character varying AS
$BODY$
declare vid integer;
declare vendor character varying;
BEGIN
vid := (select v_id from public.gc_alerts where a_id = id);
vendor := (select v_name from public.gc_vendors where v_id = vid);
RETURN vendor;
END;
$BODY$
LANGUAGE plpgsql;
I know that I can combine this into one query, but this is more of a practice exercise. This works fine and I get the vendor name. However, I need to return more than one column from the gc_vendors table.
Ultimately, I need to return columns from several tables based on subqueries. I've looked into creating a result set function, but I believe it only returns one row at a time. I also looked into returning setof type, but that seems to be limited to existing tables.
After initial feedback, I changed the function to the following:
CREATE OR REPLACE FUNCTION sql_with_rows14(IN v_uid character varying, IN lid integer)
RETURNS table (aid int, aname character varying) AS
$BODY$
declare aid integer;
declare aname character varying;
BEGIN
sql_with_rows14.aid := (select a_id from public.gc_alerts where v_id = sql_with_rows14.v_uid);
sql_with_rows14.aname := (select a_name from public.gc_alerts where a_id = sql_with_rows14.aid);
RETURN;
END;
$BODY$
LANGUAGE plpgsql;
I also tried RETURN NEXT, but same results.
When I query it, if the query returns only one row, it works fine. However it doesn't work for multiple rows. I also tried something like this, with the same result:
...
BEGIN
sql_with_rows14.aid := (select a_id from public.gc_alerts);
sql_with_rows14.aname := (select a_name from public.gc_alerts);
RETURN NEXT;
END;
I need to return more than one column from the gc_vendors table
To return a single row with multiple fields (as opposed to a set of rows), you can either use:
RETURNS row_type
.. where row_type is a pre-defined composite type (like a table name, that serves as such automatically). Or:
RETURNS record
combined with OUT parameters. Be aware that OUT parameters are visible in the body almost everywhere and avoid naming conflicts.
Using the second option, your function could look like this:
CREATE OR REPLACE FUNCTION sql_with_columns(IN _id integer -- IN is optional default
, OUT vid integer
, OUT vendor text)
RETURNS record
LANGUAGE plpgsql AS
$func$
BEGIN
SELECT INTO vid v_id
FROM public.gc_alerts
WHERE a_id = id;
SELECT INTO vendor v_name
FROM public.gc_vendors
WHERE v_id = vid;
RETURN; -- just noise, since OUT parameters are returned automatically
END
$func$;
As you mentioned, you should combine both queries into one, or even use a plain SQL statement instead. This is just a show case. The excellent manual has all the details.
You can also use:
RETURNS TABLE (...)
Or:
RETURNS SETOF row_type
This allows to return a set of rows (0, 1 or many). But that's not in your question.
To get individual columns instead of a record representation, call the function with:
SELECT * FROM sql_with_columns(...);
There are lots of examples here on SO, try a search - maybe with additional key words.
Also read the chapter "Returning from a Function" in the manual.
First of all, consider using views or simple queries. I'd say that if you can process something with a simple query, you shouldn't create function for that. in your case, you can use this query
select
v.v_name, v.* -- or any other columns from gc_alerts or gc_vendors
from public.gc_alerts as a
inner join public.gc_vendors as v on v.v_id = a.vid
where a.a_id = <your id here>
if you want your function to return rows, you can declare it like
CREATE OR REPLACE FUNCTION sql_with_rows11(id integer)
RETURNS table(vendor text, v_id int)
as
$$
select
v.v_name, v.v_id
from public.gc_alerts as a
inner join public.gc_vendors as v on v.v_id = a.vid
where a.a_id = id
$$ language SQL;
or plpgsql function:
CREATE OR REPLACE FUNCTION sql_with_rows11(id integer)
RETURNS table(vendor text, vid int)
AS
$$
declare vid integer;
declare vendor character varying;
BEGIN
sql_with_rows11.vid := 1; -- prefix with function name because otherwise it would be declared variables
sql_with_rows11.vendor := 4;
return next;
sql_with_rows11.vid := 5;
sql_with_rows11.vendor := 8;
return next;
END;
$$ LANGUAGE plpgsql;
sql fiddle demo to fiddle with :)

Function to DELETE rows taking the tablename as parameter

I want create a function:
CREATE OR REPLACE FUNCTION medibv.delAuto(tableName nvarchar(50), columnName nvarchar(100),value
nvarchar(100))
RETURNS void AS
$BODY$
begin
DELETE from tableName where columnName=value
end;
$BODY$
LANGUAGE plpgsql VOLATILE;
I have these parameters: tableName, columnName, value.
I want tableName as table in PostgreSQL.
CREATE OR REPLACE FUNCTION medibv.delauto(tbl regclass, col text, val text
,OUT success bool)
RETURNS bool AS
$func$
BEGIN
EXECUTE format('
DELETE FROM %s
WHERE %I = $1
RETURNING TRUE', tbl, col)
USING val
INTO success;
RETURN; -- optional in this case
END
$func$ LANGUAGE plpgsql;
Call:
SELECT medibv.delauto('myschema.mytbl', 'my_txt_col', 'foo');
Returns TRUE or NULL.
There is no nvarchar type in Postgres. You may be thinking of SQL Server. The equivalent would be varchar, but most of the time you can simply use text.
regclass is a specialized type for registered table names. It's perfect for the case an prevents SQL injection for the table name automatically and most effectively. More in the related answer below.
The column name is still prone to SQL injection. I sanitize the function with format(%I).
format() requires PostgreSQL 9.1+.
Your function did not report what happened. One or more rows may be found and deleted. Or none at all. As a bare minimum I added a boolean OUT column which will be TRUE if one or more rows were deleted. Because (quoting the manual here):
If multiple rows are returned, only the first will be assigned to the INTO variable.
Lastly, use USING with EXECUTE to pass in values. Don't cast back and forth. This is inefficient and prone to errors and to SQLi once more.
Find more explanation and links in this closely related answer:
Table name as a PostgreSQL function parameter
Use EXECUTE to run dynamic commands:
CREATE OR REPLACE FUNCTION medibv.delAuto(tableName nvarchar(50), columnName nvarchar(100),value
nvarchar(100))
RETURNS void AS
$BODY$
begin
EXECUTE 'DELETE FROM ' || tableName || ' WHERE ' || columnName || '=' || value;
end;
$BODY$
LANGUAGE plpgsql VOLATILE;

Can I make a plpgsql function return an integer without using a variable?

Something like this:
CREATE OR REPLACE FUNCTION get(param_id integer)
RETURNS integer AS
$BODY$
BEGIN
SELECT col1 FROM TABLE WHERE id = param_id;
END;
$BODY$
LANGUAGE plpgsql;
I would like to avoid a DECLARE just for this.
Yes you can. There are a number of ways.
1) RETURN (SELECT ...)
CREATE OR REPLACE FUNCTION get_1(_param_id integer)
RETURNS integer
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN _param_id;
-- Or:
-- RETURN (SELECT col1 FROM tbl WHERE id = _param_id);
END
$func$;
2) Use an OUT or INOUT parameter
CREATE OR REPLACE FUNCTION get_2(_param_id integer, OUT _col1 integer)
-- RETURNS integer -- is optional noise in this case
LANGUAGE plpgsql AS
$func$
BEGIN
SELECT INTO _col1 col1 FROM tbl WHERE id = _param_id;
-- also valid, but discouraged:
-- _col1 := col1 FROM tbl WHERE id = _param_id;
END
$func$;
More in the manual here.
3) (Ab)use IN parameter
Since Postgres 9.0 you can also use input parameters as variables. The release notes for 9.0:
An input parameter now acts like a local variable initialized to the passed-in value.
CREATE OR REPLACE FUNCTION get_3(_param_id integer)
RETURNS integer
LANGUAGE plpgsql AS
$func$
BEGIN
SELECT INTO _param_id col1 FROM tbl WHERE id = _param_id;
RETURN _param_id;
-- Also vlaid, but discouraged:
-- $1 := col1 FROM tbl WHERE id = $1;
-- RETURN $1;
END
$func$;
Variants 2) and 3) do use a variable implicitly, but you don't have to DECLARE one explicitly (as requested).
4) Use a DEFAULT value with an INOUT parameter
This is a bit of a special case. The function body can be empty.
CREATE OR REPLACE FUNCTION get_4(_param_id integer, INOUT _col1 integer = 123)
RETURNS integer
LANGUAGE plpgsql AS
$func$
BEGIN
-- You can assign some (other) value to _col1:
-- SELECT INTO _col1 col1 FROM tbl WHERE id = _param_id;
-- If you don't, the DEFAULT 123 will be returned.
END
$func$;
INOUT _col1 integer = 123 is short notation for INOUT _col1 integer DEFAULT 123. See:
The forgotten assignment operator "=" and the commonplace ":="
5) Use a plain SQL function instead
CREATE OR REPLACE FUNCTION get_5(_param_id integer)
RETURNS integer
LANGUAGE sql AS
'SELECT col1 FROM tbl WHERE id = _param_id';
Or use use param reference $1 instead of param name.
Variant 5) one uses plain single quotes for the function body. All the same. See:
What are '$$' used for in PL/pgSQL
Insert text with single quotes in PostgreSQL
db<>fiddle here - demonstrating all (incl. call)