ERROR: missing "LOOP" at end of SQL expression - postgresql

ERROR: missing "LOOP" at end of SQL expression
CONTEXT: compilation of PL/pgSQL function "player_height_rank" near line 9
Here is my code:
CREATE OR REPLACE FUNCTION player_height_rank (irstname VARCHAR, lastname VARCHAR) RETURNS int AS $$
DECLARE
rank INTEGER := 0;
offset INTEGER := 0;
tempValue INTEGER := NULL;
r record;
BEGIN
FOR r IN SELECT ((p.h_feet * 30.48) + (p.h_inches * 2.54)) AS height, p.firstname, p.lastname
FROM players p
WHERE p.firstname = $1 AND p.lastname = $2;
ORDER BY ((p.h_feet * 30.48) + (p.h_inches * 2.54)) DESC, p.firstname, p.lastname
LOOP
IF r.height = tempValue then
offset := offset + 1;
ELSE
rank := rank + offset + 1;
offset := 0;
tempValue := r.height;
END IF;
IF r.lastname = $4 AND r.lastname = $3 THEN
RETURN rank;
END IF;
END LOOP;
-- not in DB
RETURN -1;
END;
$$ LANGUAGE plpgsql;

In your WHERE clause semicolon is superfluous
WHERE p.firstname = $1 AND p.lastname = $2; -- delete semicolon
correct that part and try again.

Related

What is the use of KEY keyword in oracle ? Do we have any alternative for KEY in postgresql

What is the use of KEY keyword in oracle .what is the equivalent for this keyword in postgresql?this is a sample code from a function mentioned in package.here .KEY is not known one because this is writter years ago , cursor variable is not supported in postgres,what are the equivalent for migrating this code to postgresql
Code:
create or replace
function Rate ( p_base_curr CHAR ,
p_orig_curr CHAR ,
p_time_string CHAR ,
p_rate_type CHAR ) returns INT as $$ declare rate INT;
LoI INTEGER;
HiI INTEGER;
mI INTEGER;
mKey VARCHAR (30);
mLKey VARCHAR (30);
i INTEGER;
cursor get_rates_c is
select
( TRIM (e.frk_category) || TRIM (e.fk_prim_currency) || TRIM (e.fk_scndry_currency) || TRIM (e.time_string) ) key ,
( e.primary_units / e.secondary_units ) Rate ,
e.to_time_string ToTS
from
xxx e
where
e.to_time_string >= TRIM ( TO_CHAR ( TO_NUMBER ( TO_CHAR ( SYSDATE,
'YYYY' ) ) - Years_To_Cache ,
'9999' ) )
order by
( TRIM (e.frk_category) || TRIM (e.fk_prim_currency) || TRIM (e.fk_scndry_currency) || TRIM (e.time_string) ) desc;
type rates_t is VARRAY (120000) of get_rates_c%ROWTYPE;
rates rates_t;
begin if p_base_curr = p_orig_curr then rate := 1;
else mLKey := TRIM (p_base_curr) || TRIM (p_orig_curr) || TRIM (p_rate_type);
mKey := mLKey || TRIM (p_time_string);
LoI := 1;
HiI := rates.COUNT;
while LoI <= HiI loop mI := ( LoI + HiI ) / 2;
-- EXIT WHEN rates ( mI ).KEY = mKey;
case
when rates (mI).key < mKey then LoI := mI + 1;
else HiI := mi - 1;
end if;
end loop;
if ( rates (mi).key <= mKey )
and ( SUBSTR ( rates (mi).key ,
1 ,
LENGTH (mLKey) ) = mLKey )
and ( p_time_string <= rates (mi).ToTS ) then rate := rates (mi).rate;
else begin
-- SQLINES LICENSE FOR EVALUATION USE ONLY
select
coalesce ( ( e.primary_units / e.secondary_units ),
-1 )
into
RATE
from
xxx e
where
e.fk_prim_currency = p_base_curr
and e.fk_scndry_currency = p_orig_curr
and p_time_string between e.time_string and e.to_time_string
and e.frk_category = p_rate_type;
exception
when others then rate := -1;
end;
end if;
end if;
case
when rate = -1 then
case
when Return_Zero_On_Missing = 1 then rate := 0;
else
end;
$$ language plpgsql;
if;
end if;
return rate;
end Rate;
It isn't a keyword in this context. You were referring to the use at:
exit when rates(mi).KEY = mKey;
Where rates is defined with:
type rates_t is VARRAY (120000) of get_rates_c%ROWTYPE;
rates rates_t;
The use of ROWTYPE means that each element of the array is a record with the same structure as a row returned by the get_rates_c cursor, which is:
cursor get_rates_c is
select
( TRIM (e.frk_category) || TRIM (e.fk_prim_currency) || TRIM (e.fk_scndry_currency) || TRIM (e.time_string) ) key ,
( e.primary_units / e.secondary_units ) Rate ,
e.to_time_string ToTS
from
xxx e
...
So rates(mi).key is the value constructed from ( TRIM (e.frk_category) || TRIM (e.fk_prim_currency) || TRIM (e.fk_scndry_currency) || TRIM (e.time_string) ) for the corresponding row from that cursor query.
So, it isn't a keyword, it's the column alias from your cursor query.

INTERVAL add i day is not working in postgresql

I have a table like this:
CREATE TABLE DateInsert(
DateInsert timestamp without time zone,
DateInt integer NOT NULL
);
I want insert list day from 2018-01-01 to 2045-05-18 but it give me an erro
"invalid input syntax for type interval:"
CREATE OR REPLACE FUNCTION insertdate() RETURNS integer AS $$
DECLARE i integer := 0;
d timestamp without time zone := '2018-01-01';
di integer := 0;
BEGIN
while i <10000
LOOP
d := d + INTERVAL ''+ i::character varying + ' day';
di := to_char(d , 'yyyymmdd')::int;
insert into DateInsert(DateInsert,DateInt) values(d, di);
i := i+1;
END LOOP ;
return i;
END;
$$ LANGUAGE plpgsql;
How can I insert to db with timestamp increase 1 in n day loop?
Code In sql server has been working.
declare #i int=0
declare #d datetime
declare #di int = 0
while #i <10000
begin
set #d = DATEADD(DAY, #i, '2018-01-01')
set #di = cast(CONVERT(VARCHAR(10), #d, 112) as int)
insert into DateInsert(DateInsert,DateInt) values(#d, #di)
set #i = #i+1
end
The concatenation operator is || not +. And the prefixed form doesn't seem to like anything else than literals. But you can cast the concatenation expression.
So changing
...
d := d + INTERVAL ''+ i::character varying + ' day';
...
to
...
d := d + (i || ' day')::interval;
...
should work for you.

Oracle to Postgres Conversion trouble shooting

Converted a Standalone Procedure from Oracle to Postgres but not sure why there is an run error even the code is successfully compiled
Converted the below code from Oracle to Postgres
CREATE OR REPLACE FUNCTION ssp2_pcat.pop_hoa_contracts_for_prod(
)
RETURNS void
LANGUAGE 'plpgsql'
COST 100
VOLATILE
AS $BODY$
DECLARE
C1 CURSOR for
SELECT MARKET_CODE, CONTRACT_COMBO_ID, COUNT(*) FROM
ssp2_pcat.VPF_HOA_CONTRACTS_FOR_PROD A
WHERE start_Date IN
(SELECT MAX(start_date)
FROM VPF_HOA_CONTRACTS_FOR_PROD b
WHERE A.MARKET_CODE = b.MARKET_CODE
AND A.CONTRACT_COMBO_ID = b.CONTRACT_COMBO_ID
AND A.CONTRACT_ID = B.CONTRACT_ID
AND b.start_date <= current_date
AND b.end_date > current_date )
GROUP BY MARKET_CODE, CONTRACT_COMBO_ID
ORDER BY MARKET_CODE, CONTRACT_COMBO_ID;
C2 CURSOR(iMktCode VARCHAR, iCombo integer) for
SELECT MARKET_CODE, CONTRACT_COMBO_ID, CONTRACT_ID
FROM ssp2_pcat.VPF_HOA_CONTRACTS_FOR_PROD A
WHERE start_Date IN
(SELECT MAX(start_date)
FROM ssp2_pcat.VPF_HOA_CONTRACTS_FOR_PROD b
WHERE A.MARKET_CODE = b.MARKET_CODE
AND A.CONTRACT_COMBO_ID = b.CONTRACT_COMBO_ID
AND A.CONTRACT_ID = B.CONTRACT_ID
AND b.start_date <= current_date
AND b.end_date > current_date )
AND MARKET_CODE = iMktCode
AND CONTRACT_COMBO_ID = iCombo
ORDER BY MARKET_CODE, CONTRACT_COMBO_ID, START_DATE;
Contracts VARCHAR(32000);
Contract_Val1 VARCHAR(4000) := NULL;
Contract_Val2 VARCHAR(4000) := NULL;
Contract_Val3 VARCHAR(4000) := NULL;
Contract_Val4 VARCHAR(4000) := NULL;
Contract_Val5 VARCHAR(4000) := NULL;
Contract_Val6 VARCHAR(4000) := NULL;
Contract_Val7 VARCHAR(4000) := NULL;
Contract_Val8 VARCHAR(4000) := NULL;
Num INTEGER;
Cont_Num INTEGER;
l_start TIMESTAMP := clock_timestamp();
l_end TIMESTAMP := clock_timestamp();
Time_Taken VARCHAR(20);
i record;
j record;
BEGIN
l_start := clock_timestamp();
DELETE FROM ssp2_pcat.HOA_CONTRACTS_KH;
FOR i IN C1 LOOP
BEGIN
Num := 0;
Contracts := NULL;
Cont_Num := 1;
FOR j IN C2 (i.MARKET_CODE, i.CONTRACT_COMBO_ID) LOOP
Num := Num + 1;
IF Num = 1 THEN
Contracts := '|' || j.CONTRACT_ID || '|';
ELSE
IF LENGTH(Contracts || j.CONTRACT_ID || '|') > 4000 THEN
PERFORM ssp2_pcat.Assign (Cont_Num, SUBSTRING(Contracts, 1,
LENGTH(Contracts)-1));
Num := 1;
Contracts := '|' || j.CONTRACT_ID || '|';
Cont_Num := Cont_Num + 1;
ELSE
Contracts := Contracts || j.CONTRACT_ID || '|';
END IF;
END IF;
END LOOP;
PERFORM ssp2_pcat.Assign (Cont_Num, Contracts);
IF Cont_Num > 5 THEN
raise notice'%', ('MARKET_CODE: ' || i.MARKET_CODE || ', CONTRACT_COMBO_ID: ' || i.CONTRACT_COMBO_ID || ' has more than 32K in size. These Contracts are left out: ' || Contracts);
END IF;
INSERT INTO HOA_CONTRACTS_KH
(
MARKET_CODE,
CONTRACT_COMBO_ID,
CONTRACT_ID,
CONTRACT_ID2,
CONTRACT_ID3,
CONTRACT_ID4,
CONTRACT_ID5,
LAST_UPDATED
)
VALUES
(
i.MARKET_CODE,
i.CONTRACT_COMBO_ID,
Contract_Val1,
Contract_Val2,
Contract_Val3,
Contract_Val4,
Contract_Val5,
CURRENT_TIMESTAMP::TIMESTAMP(0)
);
Contract_Val1 := NULL;
Contract_Val2 := NULL;
Contract_Val3 := NULL;
Contract_Val4 := NULL;
Contract_Val5 := NULL;
Contract_Val6 := NULL;
Contract_Val7 := NULL;
Contract_Val8 := NULL;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
raise notice'%', ('1) POP_HOA_CONTRACTS_FOR_PROD: ' || SQLERRM);
END;
END LOOP;
RAISE NOTICE 'Function excution time Took: %', l_start;
RAISE NOTICE 'Function excution time Took: %',l_end-l_start;
SELECT l_end-l_start INTO Time_Taken;
raise notice'%',('POP_HOA_CONTRACTS_FOR_PROD Took: ' || Time_Taken );
EXCEPTION
WHEN OTHERS THEN
raise notice'%', ('2) POP_HOA_CONTRACTS_FOR_PROD: ' || SQLERRM);
END;
$BODY$;
The code is compiled successfully, but giving a run time error as follows,
NOTICE: 2) POP_HOA_CONTRACTS_FOR_PROD: cannot begin/end transactions in PL/pgSQL
Debugged the whole code and looks like still I'm unable to identify the issue, can any one help me in making me understand more about Postgres as I'm new to this Database. Found out in unit testing that its not calling the assign function mentioned in the code,

get rank of players' height in plpgsql

We are going to have the rank of height, but I got 0 for all players
I convert the feet and inches into cm first, and use the sample code teacher gave us.
Here is my code:
CREATE OR REPLACE FUNCTION player_height_rank (firstname VARCHAR, lastname VARCHAR) RETURNS int AS $$
DECLARE
rank INTEGER:= 0;
offset INTEGER:= 0;
tempValue FLOAT:= NULL;
r record;
BEGIN
FOR r IN SELECT ((p.h_feet * 30.48) + (p.h_inches * 2.54)) AS height, p.firstname, p.lastname
FROM players p
ORDER BY ((p.h_feet * 30.48) + (p.h_inches * 2.54)) DESC, p.firstname, p.lastname
LOOP
IF r.height = tempValue then
offset := offset + 1;
ELSE
rank := rank + offset + 1;
offset := 0;
tempValue := r.height;
END IF;
IF r.firstname = $1 AND r.lastname = $2 THEN
RETURN rank;
END IF;
END LOOP;
-- not in DB
RETURN 0;
END;
$$ LANGUAGE plpgsql;
--select * from player_height_rank('Ming', 'Yao');
Your function works fine for me if I correct two bugs:
One of your commas is not really a comma, but a “fullwidth comma”, UNICODE code point FF0C, which causes a syntax error.
You have a variable name offset, which causes SQL syntax errors because it is a reserved key word in SQL. If you really need to use that name, you have to enclose it in double quotes (") throughout, but it is better to choose a different name.
The reason this causes a problem is that an assignment like offset := offset + 1; in PL/pgSQL is translated into an SQL statement like SELECT offset + 1 INTO offset;.
You can do the whole thing in a single SQL query, which is more efficient:
SELECT rank
FROM (SELECT firstname,
lastname,
rank() OVER (ORDER BY h_feet + 12 * h_inches)
FROM players
) dummy
WHERE firstname = 'Ming'
AND lastname = 'Yao';

How can I return optional results from a dynamic query in a plpgsql function?

I'm playing around with plpgsql and have put together a function that assembles a dynamic query. I've tested it and it executes (i've included a test wrapper to output the assembled query).
Where I'm stumbling is capturing the output of the EXECUTE command once it's run, because I'd like to return some or all of the values, depending on the nature of the dynamic query. I've set up a type userprofile, and have the setProfileDynamic function return this type.
With the full complement of parameters, the output checks out (except for the second query, more on that in a bit). But when some of the parameters are missing (ie not all the user preferences are updated, only one eg: measuresystem) then the output is corrupted, so that measuresystem_id might appear as username in the output.
Secondly, is how to get the result of the second query (updateDefaultMealplan) into the userprofile type (where the columns mealplan_id and mealplan_name are waiting patiently). Currently this query returns into mp_id (and mp_name is filled from the _values array if 'defaultmealplan' key is present).
I'm quite new to this and I might be trying to do too much in one function, and I might be doing it completely the wrong way, so I don't mind whatever corrections might come to pass.
The userprofile type:
DROP TYPE IF EXISTS userprofile CASCADE;
CREATE TYPE userprofile AS (
username text,
measuresystem_id int,
blanksymbol_id int,
mealplan_id int,
mealplan_name text
);
The main function
DROP FUNCTION IF EXISTS setProfileDynamic (int, text, text[], text[]);
CREATE OR REPLACE FUNCTION setProfileDynamic (_userid int, _token text, _keys text[], _values text[])
RETURNS userprofile AS $$
DECLARE
_query text;
numkeys int;
i int;
_update text[];
_from text[];
_where text[];
_return text[];
_into text[];
test text[];
up userprofile;
mp_name text;
mp_id int;
u text;
f text;
w text;
r text;
c_update int := 1;
c_from int := 1;
c_where int := 3;
c_return int := 1;
runupdate boolean := false; --bc passing default mealplan through this fn too.
changedefaultmp boolean := false;
BEGIN
test[1] := 'users.id';
test[2] := 'users.token';
test[3] := _userid;
test[4] := _token;
numkeys := array_length(_keys, 1);
raise notice 'numkeys = %', numkeys;
_where[1] := test[1] || ' = ' || quote_literal(test[3]);
_where[2] := test[2] || ' = ' || quote_literal(test[4]);
--raise notice '_where[1] = %', _where[1];
--raise notice '_where[2] = %', _where[2];
for i in 1..numkeys loop
raise notice 'keys[%] = %', i, _keys[i];
CASE _keys[i]
WHEN 'email' THEN
runupdate := true;
_update[c_update] := quote_ident(_keys[i]) || ' = ' || quote_literal(_values[i]);
c_update := c_update + 1;
WHEN 'password' THEN
runupdate := true;
_update[c_update] := quote_ident(_keys[i]) || ' = ' || quote_literal(_values[i]);
c_update := c_update + 1;
WHEN 'username' THEN
runupdate := true;
_update[c_update] := quote_ident(_keys[i]) || ' = ' || quote_literal(_values[i]);
c_update := c_update + 1;
_return[c_return] := quote_ident(_keys[i]);
c_return := c_return + 1;
WHEN 'measuresystem' THEN
runupdate := true;
_update[c_update] := 'measuresystem_id = ms.id';
c_update := c_update + 1;
_from[c_from] := 'measuresystem as ms';
c_from := c_from + 1;
_where[c_where] := 'ms.name = ' || quote_literal(_values[i]);
c_where := c_where + 1;
_return[c_return] := 'ms.id';
c_return := c_return + 1;
WHEN 'blanksymbol' THEN
runupdate := true;
_update[c_update] := 'blanksymbol_id = bs.id';
c_update := c_update + 1;
_from[c_from] := 'blanksymbol as bs';
c_from := c_from + 1;
_where[c_where] := 'bs.name = ' || quote_literal(_values[i]);
c_where := c_where + 1;
_return[c_return] := 'bs.id';
c_return := c_return + 1;
ELSE
changedefaultmp := true;
mp_name := _values[i];
END CASE;
end loop;
u := 'UPDATE users SET ' || array_to_string(_update, ', ');
f := 'FROM ' || array_to_string(_from, ', '); --if a_t_s is null, the whole f is null and not included so no error
w := 'WHERE ' || array_to_string(_where, ' AND ');
r := 'RETURNING ' || array_to_string(_return, ', ');
raise notice 'u = %', u;
raise notice 'f = %', f;
raise notice 'w = %', w;
raise notice 'r = %', r;
_query = concat_ws(' ', u, f, w, r);
raise notice '_query = %', _query;
IF runupdate THEN
if r IS NULL THEN
EXECUTE _query;
ELSE
EXECUTE _query INTO up;
END IF;
END IF;
IF changedefaultmp THEN
SELECT into mp_id updateDefaultMealplan(_userid, mp_name);
END IF;
return up;
END
$$ LANGUAGE PLPGSQL;
This is the wrapper function where you can see the query generated for different inputs:
DROP FUNCTION IF EXISTS T ();
CREATE OR REPLACE FUNCTION T ()
RETURNS setof userprofile AS $$
declare
_keys text[];
_values text[];
_userid int := 1;
_token text := 'beet';
begin
_keys := ARRAY['email', 'password', 'username', 'measuresystem', 'blanksymbol', 'defaultmealplan'];
_values := ARRAY['s#p.com', 'secret', 'myname', 'metric', '?', 'new'];
--_keys := ARRAY['email', 'blanksymbol'];
--_values := ARRAY['k#d.com', '[]'];
return query
SELECT * from setProfileDynamic(_userid, _token, _keys, _values);
end
$$ LANGUAGE PLPGSQL;
I realize it's a lot of code to get through, I hope the T function helps to clarify things. 'email' and 'password' params are not returning. 'defaultmealplan' triggers the second query. Any of 'username', 'measuresystem', 'blanksymbol' or 'defaultmealplan' should return a value into the userprofile type. Thanks for any forthcoming feedback.
the basic issue is so your dynamic query doesn't returns all necessary columns, second issue - you probably expecting, but it is not valid expectation, so records are assigned with respecting field' names. But when you assign some values to some composite type, postgres dosn't check name - only order is important. So you have to use NULLs for filling gaps and return all field.
you can simplify your code with array concating
DECLARE _return_cols text[] = '{}';
BEGIN
_return_cols := _return_cols || quote_ident('some_column');
_return_cols := _return_cols || quote_ident('some_other_column');
...