Cursor in pgsql (postgres) - sql

Again I appeal to you for your help. I am migrating processes from Oracle to postgres.
I declare this cursor to extract an information and insert it into a table:
esi_cur_fono cursor
for SELECT (select nextval('edef_seq_pr')) seq_nextval,
c_pcodigo_soc_dest,
c_ctac_correlativo,
c_transac,
c_transac||
lpad(c_tr_count, v_transaction_seq,'0')||
lpad(c_rc_count, v_record_seq,'0')||
rpad(esi.pers_codigo, v_exploitation_source_id,' ')||
rpad(translate(esi.nombre,c_cad_n,c_cad_y), v_exploitation_source_name,' ')||
rpad(esi.esty, v_exploitation_source_type,' ')||
lpad(c_tisn_cd, v_exploitation_territory_code,'0')||
lpad(c_tisn_fd, v_exploitation_territory_cvfd,'0')||
rpad(c_tisan, v_exploitation_territory_abbn,' ')||
lpad(c_tisn_fd, v_exploitation_territory_avfd,'0'),
now() fecha,
tipo_dist,
(SELECT currval('edef_seq_pr')) edef_padre,
c_edef_order,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
FROM (SELECT DISTINCT liprt.pers_codigo,
pers.pers_nombre_completo nombre,
'10' esty,
'MEC' tipo_dist
FROM mocct a
INNER JOIN reort b ON a.reor_correlativo = b.reor_correlativo
INNER JOIN deret c ON c.dere_correlativo = b.dere_correlativo
INNER JOIN dblink('dbname = crd host=100.1.1.138 port=5432', 'select delp_correlativo, lipr_correlativo from fon_detalles_liq_productor') as delpt (delp_correlativo numeric, lipr_correlativo numeric) ON delpt.delp_correlativo = c.delp_correlativo
INNER JOIN dblink('dbname = crd host=100.1.1.138 port=5432', 'select lipr_correlativo, pers_codigo from fon_liquidaciones_productor') as liprt (lipr_correlativo numeric, pers_codigo varchar) ON liprt.lipr_correlativo = delpt.lipr_correlativo
INNER JOIN dblink('dbname = usuarios host=100.1.1.138 port=5432', 'select pers_codigo, pers_nombre_completo from unv_personas') as pers (pers_codigo varchar, pers_nombre_completo varchar) ON liprt.pers_codigo = pers.pers_codigo
WHERE a.mocc_monto != 0
AND b.pers_codigo_socadm = '312951160'
AND a.ctac_correlativo = 7344) esi;
The problem is presented in the declaration of the variables where the values returned by the cursor are saved, since not being a table, but a sub query, I get an error, so I resort to declare the variables with the type and the length maximum for each one.
/*declaration of cursor variables*/
v_seq_nextval numeric(10);
v_c_pcodigo_soc_dest varchar(10);
v_c_ctac_correlativo varchar(10);
v_c_transac varchar(10);
v_registro varchar(218);
v_fecha date;
v_tipo_dist varchar(10);
v_edef_padre numeric(10);
v_c_edef_order numeric(1);
v_null_1 varchar(10);
v_null_2 varchar(10);
v_null_3 varchar(10);
v_null_4 varchar(10);
v_null_5 varchar(10);
v_null_6 varchar(10);
v_null_7 varchar(10);
v_null_8 varchar(10);
When I execute it, it gives me the following error
ERROR: Missing "FROM or IN" at the end of the SQL expression
LINE 107: FETCH esi_cursor_fono INTO v_seq_nextval;
^
SQL state: 42601
Character: 4897
Look everywhere, and all the examples are with tables, and even I already have 2 that work without problem, but it is because the queries are direct to tables, not to sub queries.

Not sure what you're doing inside your FOR loop, but here's an example you can use and adapt to your needs:
CREATE OR REPLACE FUNCTION DCPViews.SP_DCPDeleteSchool (
pSchoolId INTEGER
)
RETURNS VOID AS $$
DECLARE
myclass RECORD;
BEGIN
-- Cascaded DELETEs (must delete from child tables first)
-- Delete all classes associated with school
FOR myclass IN
SELECT ClassId FROM DCP.Class WHERE SchoolId = pSchoolId
LOOP
PERFORM DCPViews.SP_DCPDeleteClass(myclass.ClassId); -- PERFORM runs function and discards the results
END LOOP;
-- Delete school
DELETE FROM DCP.School WHERE SchoolId = pSchoolId;
-- Ignore foreign key violation errors
EXCEPTION WHEN foreign_key_violation THEN NULL;
END;
$$ LANGUAGE 'plpgsql';
You don't need to store the values into variables, you just create a new RECORD variable which stores each current row of your FOR loop SELECT statement as it's being processed.
Let me know if that's what you're looking for or if I misread your question.

Related

Stored procedure can not be called due to syntax error

We migrated from SQL Server to Postgres and I am trying to rewrite a stored procedure. The procedure is created correctly, but I can not call it.
This is my procedure:
CREATE OR REPLACE PROCEDURE spr_getItems (
p_kind int = NULL,
p_customerId varchar(256) = NULL,
p_resourceIds varchar(2048) = NULL,
p_referenceIds varchar(2048) = NULL
)
AS $$
BEGIN
SELECT
c.kind,
c.name AS customerName,
c.oid AS customerId,
r.name AS resourceName,
r.oid AS resourceId
o.fullObject AS fullObjectString
FROM m_customer c
JOIN m_resource r
ON r.oid = c.resourceOid
LEFT JOIN m_object o
ON o.customerOid = c.oid
AND o.customerOid = p_customerId
WHERE (c.kind = p_kind OR p_kind is NULL)
AND (c.referenceOid IN (SELECT refTemp.oid FROM tvf_commaSeperatedStringToTable(p_referenceIds) refTemp) OR p_referenceIds is NULL)
AND (r.oid IN (SELECT resTemp.oid FROM tvf_commaSeperatedStringToTable(p_resourceIds) resTemp) OR p_resourceIds is NULL);
END;
$$
LANGUAGE 'plpgsql';
the table-valued-function tvf_commaSeperatedStringToTable just takes a string, splits it and returns a table with all of the different ids and a rownumber. It works just fine and is tested, no errors inside here.
Now when I try to execute it like this
CALL public.spr_getItems (0, null, null, null)
I get this output:
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function spr_getItems(integer,character varying,character varying,character varying) line 3 at SQL statement
SQL state: 42601
But I do NOT want to discard the result, I want to see them.
So I tried calling it with select
SELECT *
FROM CALL spr_getItems (0, null, null, null)
and then I get this syntax error:
ERROR: syntax error at or near "0"
LINE 2: 0,
^
SQL state: 42601
Character: 40
I also tried executing it in several other way eg by adding the "public." before the procedures name, but then there has been a syntax error at the ".". Or with just using select spr_getItems(0, null, null, null) or select spr_getItems(0), select * from call spr_getItems (0) and so on and so forth.
Am I doing something completely wrong and overlooked something in the documentation?
Thanks for any help!
Edit: clarification that I want to see the results
Edit2: accidentally copied a wrong function name
Edit3: added complete body as suggested
That's not how Postgres works. Procedures aren't meant to return result sets.
If you want that use a set returning function:
CREATE OR REPLACE function spr_getItems (
p_kind int = NULL,
p_customerId varchar(256) = NULL,
p_resourceIds varchar(2048) = NULL,
p_referenceIds varchar(2048) = NULL
)
returns table (kind text, customername text, customerid integer, resourcename text, resourceid integer, fullobjectstring text)
AS $$
SELECT
c.kind,
c.name AS customerName,
c.oid AS customerId,
r.name AS resourceName,
r.oid AS resourceId
o.fullObject AS fullObjectString
FROM m_customer c
JOIN m_resource r
ON r.oid = c.resourceOid
LEFT JOIN m_object o
ON o.customerOid = c.oid
AND o.customerOid = p_customerId
WHERE (c.kind = p_kind OR p_kind is NULL)
AND (c.referenceOid IN (SELECT refTemp.oid FROM tvf_commaSeperatedStringToTable(p_referenceIds) refTemp) OR p_referenceIds is NULL)
AND (r.oid IN (SELECT resTemp.oid FROM tvf_commaSeperatedStringToTable(p_resourceIds) resTemp) OR p_resourceIds is NULL);
$$
LANGUAGE sql;
You also don't need PL/pgSQL for a simple query encapsulation, language sql will do just fine.
Then use it like a table:
select *
from spr_getitems(....);
Note that I guessed the data types in the returns table (...) part, you will have to adjust that to the real types used in your tables.
You don't need the sub-selects to handle the comma separated values either.
E.g. this:
AND (c.referenceOid IN (SELECT refTemp.oid FROM tvf_commaSeperatedStringToTable(p_referenceIds) refTemp) OR p_referenceIds is NULL)
can be simplified to
AND (c.referenceOid = any (string_to_array(p_referenceIds, ',') OR p_referenceIds is NULL)
But passing multiple values as a comma separated string is bad coding style to begin with. You should declare those parameters as array and pass proper arrays to the function.
The error refers to a function call (spr_getshadowrefs) inside the public.spr_getItems procedure. Perhaps you're trying to execute the spr_getshadowrefs function without putting the result in any variable.
Try to use PERFORM when you execute the spr_getshadowrefs function inside the public.spr_getItems procedure.
Have you tried
EXEC spr_getItems p_kind = 0,
p_customerId = NULL,
p_resourceIds = NULL,
p_referenceIds = NULL

Dynamic SQL (where) in Firebird stored procedure

I Have an SP that receive 2 parameters, P1 and P2, like this:
CREATE OR ALTER PROCEDURE MY_PROC (P1 varchar(10), P2 smallint = 1)
RETURNS (
code VARCHAR(10),
name VARCHAR(70),
state VARCHAR(2),
situation VARCHAR(20)
AS
...
...
And I need to generate the where clause based on the P2 parameter, like this:
if (P2=1) then
where (state='SP' and situation='stopped')
elseif (P2=2)
where (state='MG' and situation='moving')
How to use this type of if statement in where clause?
To me your question translates as a simple OR condition in the WHERE clause of a SQL query:
WHERE
(:P2 = 1 AND state='SP' and situation='stopped')
OR (:P2 = 2 AND state='MG' and situation='moving')
The answer of GMB will work fine for most situations, but in more complex cases it may have less desirable performance. An alternative solution would be to build a query string dynamically and execute it with execute statement:
CREATE OR ALTER PROCEDURE MY_PROC (P1 varchar(10), P2 smallint = 1)
RETURNS (
code VARCHAR(10),
name VARCHAR(70),
state VARCHAR(2),
situation VARCHAR(20)
AS
declare query varchar(2048);
begin
query = 'select ......';
if (p2 = 1) then
query = query || ' where (state=''SP'' and situation=''stopped'')';
else if (p2 = 2) then
query = query || ' where (state=''MG'' and situation=''moving'')';
-- if you expect a single result
execute statement query into code, name, state, situation;
-- OR
-- for multiple results
for execute statement query into code, name, state, situation do
suspend;
end

How to check only the first value of the row returned from stored procedure in a SQL query

If I have a stored procedure like this:
get_my_dep(empNum)
and it returns one row ex:
call get_my_dep(567);
dep_code dep_year dep_name
66 2017 HR
How can I check only the first value of the row (dep_code) in my query like this:
SELECT *
FROM rmcandidate a INNER JOIN task b
ON a.task_code = b.task_code
WHERE get_my_dep(emp_num) != 0 -- here I want to check only the dep_code
AND b.active_flag = 1
Presumably the stored procedure is defined as returning multiple values as in:
create procedure get_my_dep(emp_num int)
returning int as dep_code, int as dep_year, char(8) as dep_name;
In this case you could create a wrapper procedure that returns only one of the values and then use that in the WHERE clause. For example:
create procedure get_my_dep_code(emp_num int)
returning int as dep_code;
define dc, dy int;
define dn char(8);
execute procedure get_my_dep(emp_num) into dc, dy, dn;
return dc;
end procedure;
An alternative could be to define the procedure to return a row type. For example:
create row type dep_code_t(dep_code int, dep_year int, dep_name char(8));
create procedure get_my_dep(emp_num int)
returning dep_code_t;
define dc, dy int;
define dn char(8);
...
return row(dc, dy, dn)::dep_code_t;
end procedure;
It is then possible to directly reference an element of the returned row type in a WHERE clause as in:
WHERE get_my_dep(emp_num).dep_code != 0
You can try using a virtual table:
SELECT
*
FROM
rmcandidate AS a
INNER JOIN task AS b
ON
a.task_code = b.task_code
WHERE
b.active_flag = 1
AND 0 !=
(
SELECT
vt1.dep_code
FROM
TABLE (get_my_dep(emp_num)) AS vt1 (dep_code, dep_year, dep_name)
)
;
This was tested on Informix 12.10 .

How to process SQL string char-by-char to build a match weight?

The problem: I need to display fields for user entry on a form, dynamic to some lookup criteria.
My current solution: I've created a SQL table with some field entry criteria, based on a relatively simple matching criteria. The match criteria basically is such that Lookup Value starts with Match Code, and the most precise match is found by doing a LEN comparison.
select
f.[IS_REQUIRED]
, f.[MASK]
, f.[MAX_LENGTH]
, f.[MIN_LENGTH]
, f.[RESOURCE_KEY]
, f.[SEQUENCE]
from [dbo].[MY_RECORD] r with(nolock)
inner join [dbo].[ENTRY_FORMAT] f with(nolock)
on r.[LOOKUP_VALUE] like f.[MATCH_CODE]
-- Logic to filter by single, most-precise record match.
cross apply (
select f1.[SEQUENCE]
from [dbo].[ENTRY_FORMAT] f1 with(nolock)
where f.[SEQUENCE] = f1.[SEQUENCE]
and s.[MATCH_CODE] like f1.[MATCH_CODE]
group by f1.[SEQUENCE]
having len(f.[MATCH_CODE]) = max(len(f1.[MATCH_CODE]))
) tFilter
where r.[ID] = #RecordId
Current issues with this is that the most precise match has to be calculated each and every call, against each and every match. Additionally, I'm only currently able to support the % in the MATCH_CODE. (e.g., '%' is the default for all LOOKUP_VALUE, while an entry of '12%' would be the more precise match for a LOOKUP_VALUE of '12345', and MATCH_CODE of '12345' should obviously me the most precise match.) However, I would like to add support for [4-7], etc. wildcards. Going just off of LEN, this would definitely be wrong, because '[4-7]' adds a lot to the length, but, for example '12345' is still the desired match over '123[4-7]'
My desired update: To add a MATCH_WEIGHT column to ENTRY_FORMAT, which I can update via a trigger on insert/update. For my initial implementation, I'm just looking for something that can go through MATCH_CODE, character by character, increasing MATCH_WEIGHT, but treating [..] as just a single character when doing so. Is there a good mechanism (UDF - either SQL or CLR? CURSOR?) for iterating through characters of a varchar field to calculate a value in this way? Something like increasing MATCH_WEIGHT by two per non-wildcard, and perhaps by one on a wildcard; with details to be further thought out and worked out...
The goal being to use a query more like:
select
f.[IS_REQUIRED]
, f.[MASK]
, f.[MAX_LENGTH]
, f.[MIN_LENGTH]
, f.[RESOURCE_KEY]
, f.[SEQUENCE]
from [dbo].[MY_RECORD] r with(nolock)
-- Logic to filter by single, most-precise record match.
cross apply (
select top 1
f1.[MATCH_CODE]
, f1.[SEQUENCE]
from [dbo].[ENTRY_FORMAT] f1 with(nolock)
where r.[LOOKUP_VALUE] like f1.[MATCH_CODE]
group by f1.[SEQUENCE]
order by f1.[MATCH_WEIGHT] desc
) tFilter
inner join [dbo].[ENTRY_FORMAT] f with(nolock)
on f.[MATCH_CODE] = tFilter.[MATCH_CODE]
and f.[SEQUENCE] = tFilter.[SEQUENCE]
where r.[ID] = #RecordId
Note: I realize this is a relatively fragile setup. The ENTRY_FORMAT records are only entered by developers, who are aware of the restrictions, so for now assume that valid data is entered, and which does not cause match collisions.
With some help, I've come up with one implementation (answer below), but am still unsure as to my total design, so welcoming better answers or any criticism.
From Steve's answer on another question, I've used much of the body to create a function to accomplish support for the [..] wildcard at the end of a match code.
CREATE FUNCTION CalculateMatchWeight
(
-- Add the parameters for the function here
#MatchCode varchar(100)
)
RETURNS smallint
AS
BEGIN
-- Declare the return variable here
DECLARE #Result smallint = 0;
-- Add the T-SQL statements to compute the return value here
DECLARE #Pos int = 1, #N0 int = ascii('0'), #N9 int = ascii('9'), #AA int = ascii('A'), #AZ int = ascii('Z'), #Wild int = ascii('%'), #Range int = ascii('[');
DECLARE #Asc int;
DECLARE #WorkingString varchar(100) = upper(#MatchCode)
WHILE #Pos <= LEN(#WorkingString)
BEGIN
SET #Asc = ascii(substring(#WorkingString, #Pos, 1));
If ((#Asc between #N0 and #N9) or (#Asc between #AA and #AZ))
SET #Result = #Result + 2;
ELSE
BEGIN
-- Check wildcard matching, update value according to match strength, and stop calculating further.
-- TODO: In the future we may wish to have match codes with wildcards not just at the end; try to figure out a mechanism to calculating that case.
IF (#Asc = #Range)
BEGIN
SET #Result = #Result + 2;
SET #Pos = 100;
END
IF (#Asc = #Wild)
BEGIN
SET #Result = #Result + 1;
SET #Pos = 100;
END
END
SET #Pos = #Pos + 1
END
-- Return the result of the function
RETURN #Result
END
I've checked that this can generate desired output for the current cases that I'm trying to cover:
SELECT [dbo].[CalculateMatchWeight] ('12345'); -- Most precise (10)
SELECT [dbo].[CalculateMatchWeight] ('123[4-5]'); -- Middle (8)
SELECT [dbo].[CalculateMatchWeight] ('123%'); -- Least (7)
Now I can call this function in a trigger on INSERT/UPDATE to update the MATCH_WEIGHT:
CREATE TRIGGER TRG_ENTRY_FORMAT_CalcMatchWeight
ON ENTRY_FORMAT
AFTER INSERT,UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for trigger here
DECLARE #NewMatchWeight smallint = (select dbo.CalculateMatchWeight(inserted.MATCH_CODE) from inserted),
#CurrentMatchWeight smallint = (select inserted.MATCH_WEIGHT from inserted);
IF (#CurrentMatchWeight <> #NewMatchWeight)
BEGIN
UPDATE ENTRY_FORMAT
SET MATCH_WEIGHT = #NewMatchWeight
FROM inserted
WHERE ENTRY_FORMAT.[MATCH_CODE] = inserted.[MATCH_CODE]
AND ENTRY_FORMAT.[SEQUENCE] = inserted.[SEQUENCE]
END
END

SQL procedure to add and edit data

Im busy with an old exam paper one of the questions read as follows
Study the following tables and answer the questions below:
CREATE TABLE CARDHOLDERS(
CH_ID INTEGER IDENTITY,
CH_NAME VARCHAR(50),
CH_SURNAME VARCHAR(50),
CH_IDNUMBER CHAR(13),
CH_CARDNUMBER CHAR(13),
CH_STATUS CHAR(2),
CH_CREATE_DATE DATETIME,
CH_LAST_CHANGE_DATE DATETIME)
Write a store procedure to add or edit the cardholders information. Do the neccecary validation checks to ensure data is correct.
My Answer
Create Procedure add_ch (#CH_NAME, #CH_SURNAME...)
AS
BEGIN
INSERT INTO CARDHOLDERS VALUES (#CH_NAME, #CH_SURNAME...)
END
TO RUN PROCEDURE
EXECUTE add_ch ('Peter', 'Kemp')
My Question
Will the above procedure to add cardholer give the correct results?
The Question asks 'Write a store procedure to add or edit the
cardholders information' how do I combine the add procedure with
the edit cardholder procedure or am I correct in assuming that I can
have to different procedure?
Are you looking for something like this?
CREATE PROCEDURE add_ch (#CH_NAME , #CH_SURNAME...)
AS
BEGIN
DECLARE #count INT
SET #count =
(SELECT count (*)
FROM CARDHOLDERS
WHERE CH_NAME = #CH_NAME AND CH_SURNAME = #CH_SURNAME)
IF #count = 0
INSERT INTO CARDHOLDERS
VALUES (#CH_NAME, #CH_SURNAME...)
else Print'This user already exsit.'
END
Try something like this. Using decode and setting defaults for the parameters helps.
create or replace procedure add_ch
(
CHID INTEGER := -1,
CHNAME VARCHAR := '#',
CHSURNAME VARCHAR := '#',
CHIDNUMBER CHAR := '#',
CH_CARDNUMBER CHAR := '#',
CHSTATUS CHAR := '#',
CHCREATE_DATE DATETIME := '01-Jan-1900',
CHLAST_CHANGE_DATE DATETIME:= '01-Jan-1900'
)
as
begin
update cardholders
set CH_NAME = decode( CHNAME,'#',CH_NAME,chname ),
CH_SURNAME = decode( CHSURNAME,'#',CH_SURNAME, CHSURNAME),....
where CH_ID = CHID;
if sql%notfound
then
insert into cardholders
(
CH_ID,
CH_NAME,
CH_SURNAME,
CH_IDNUMBER,
CH_CARDNUMBER,
CH_STATUS,
CH_CREATE_DATE,
CH_LAST_CHANGE_DATE
)
values
(
CHID,
CHNAME,
CHSURNAME,
CHIDNUMBER,
CH_CARDNUMBER,
CHSTATUS CHAR,
CHCREATE_DATE,
CHLAST_CHANGE_DATE
);
end;
first of all You Have to find The primary key data in your database table
if exist data in DBtable(with current primary key value)
then execute your update sql query
else
execute your insert query.
Done your database checking using the previous answer to your question.