TRIGGER FUNCTION Grade Check PostgreSQL - sql

I created a scholarship database with and apply table
applyid | studid | gpa | other | sch_id | date | sem | sy
---------+-----------+-----------+-------+----------+------------+-----+----
1 | 2010-0000 | 1.5 | | 1 | | |
2 | 2010-0001 | 1.5 | | 7 | 2014-03-13 | |
3 | 2010-0003 | | | 1 | 2014-03-13 | |
4 | 2010-0003 | | | 1 | 2014-03-13 | |
5 | 2010-0003 | | | 1 | 2014-03-13 | |
2308 | 2012-0004 | 1.5 | | 1 | 2014-03-19 | |
4593 | 2012-0004 | 1.5 | | 1 | 2014-03-19 | |
4596 | 2012-0004 | 1.5 | | 1 | 2014-03-19 | |
4597 | 2012-0004 | 1.5 | | 1 | 2014-03-19 | |
(9 rows)
and currently working on this trigger function that checks if a particular student has either a grade of INC, DRP, 5.00.
CREATE FUNCTION fail_check() RETURNS TRIGGER AS $$
DECLARE
one RECORD;
two RECORD;
BEGIN
SELECT * INTO one FROM grade, registration;
IF (SELECT COUNT(g.grade)::int
FROM grade g
INNER JOIN registration r ON r.grade_id = g.grade_id
WHERE g.grade IN ('INC', 'DRP', '5.00')
AND studid=new.studid) <= 1
THEN
SELECT studid, gpa, sch_name INTO two
FROM apply WHERE studid=new.studid;
INSERT INTO apply(studid, gpa, sch_name)
VALUES (new.studid, new.gpa, new.sch_name);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER fail
BEFORE INSERT ON apply
FOR EACH ROW
EXECUTE PROCEDURE fail_check();
but when I entered this:
INSERT INTO apply(studid, gpa, sch_name)
VALUES ('2012-0004', '1.5', 1);
The student with the student id of "2012-0004" has a grade of INC DRP and 5.00. the SELECT query works perfectly fine and returns the value 3. Since 3 is greater than 1, which is contrary to the IF statement that says IF .... <= 1, I'm expecting an error that says something like that it can't be inserted because the "student" has more than 1 grade of either INC, DRP, 5.00.
But instead I got this error:
ERROR: stack depth limit exceeded
HINT: Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate.
CONTEXT: SQL statement "SELECT (SELECT COUNT(g.grade)
FROM grade g
INNER JOIN registration r ON r.grade_id = g.grade_id
WHERE g.grade IN ('INC', 'DRP', '5.00') AND studid=new.studid) <= 1" PL/pgSQL function fail_check() line 12 at IF SQL statement "INSERT INTO apply(studid, gpa, sch_name) VALUES (new.studid, new.gpa, new.sch_name)" PL/pgSQL function fail_check() line 21 at SQL statement SQL statement "INSERT INTO apply(studid, gpa, sch_name) VALUES (new.studid, new.gpa, new.sch_name)"
Where did I go wrong?? and what does this max_stack_depth exactly mean?? Which part of my code caused this max_stack_depth error??
Currently using PostgreSQL 9.3.2

Your trigger BEFORE INSERT triggers more INSERTs to the same table, which causes an endless loop. Hence the stack overflow. You seem to be under the impression that you need this in your trigger:
INSERT INTO apply(studid, gpa, sch_name)
VALUES (new.studid, new.gpa, new.sch_name);
But you don't. RETURN NEW; is enough to let the original INSERT go through.
The rest of your trigger doesn't seem to do anything useful, but that's probably just a simplification.

Related

Is there a way in Postgres / SQL to substitute characters in strings from columns where the characters in the string are column names?

I have a table called sentences, and a table called logs.
The sentences table looks like this:
|------------|---------------------------------------|
| id | sentence |
|------------|---------------------------------------|
| 1 | [var1] says hello! |
|------------|---------------------------------------|
| 2 | [var1] says [var2]! |
|------------|---------------------------------------|
| 3 | [var1] says [var2] and [var3]! |
|------------|---------------------------------------|
| 4 | [var4] says [var2] to [var1]! |
|------------|---------------------------------------|
The logs table looks like this:
|------------|------------------|--------------|--------------|--------------|--------------|
| id | sentenceId | var1 | var2 | var3 | var4 |
|------------|------------------|--------------|--------------|--------------|--------------|
| 1 | 1 | Sam | | | |
|------------|------------------|--------------|--------------|--------------|--------------|
| 2 | 2 | Joe | what's up | | |
|------------|------------------|--------------|--------------|--------------|--------------|
| 3 | 3 | Tim | hey | how are you | |
|------------|------------------|--------------|--------------|--------------|--------------|
| 4 | 4 | Joe | hi | | Tiffany |
|------------|------------------|--------------|--------------|--------------|--------------|
The result I am trying to get is:
|------------|-----------------------------------------|
| logs.id | sentences.sentence |
|------------|-----------------------------------------|
| 1 | [Sam] says hello! |
|------------|-----------------------------------------|
| 2 | [Joe] says [what's up]! |
|------------|-----------------------------------------|
| 3 | [Tim] says [hey] and [how are you]! |
|------------|-----------------------------------------|
| 4 | [Tiffany] says [hi] to [Joe] |
|------------|-----------------------------------------|
I'm not sure how to write the SQL query to make the database do the text substitutions for me.
I could just select everything from both tables using an inner join, and then loop through in code and do the substitutions myself. I.e.:
SELECT logs.id, sentences.sentence, logs.var1, logs.var2, logs.var3, logs.var4 FROM logs INNER JOIN sentences ON logs.sentenceId = sentences.id
And then in code:
logs.forEach(log => log.sentence.replace(/\[(.*?)\]/g, ($matchedString, $columnName) => log[$columnName] ))
But if possible, I'd like the database to do that for me so that I don't have to select more data than I need.
I would write a function to do that:
create function replace_vars(p_sentence text, p_vars jsonb)
returns text
as
$$
declare
l_rec record;
l_result text;
begin
l_result := p_sentence;
for l_rec in select * from jsonb_each_text(jsonb_strip_nulls(p_vars)) as x(var,value)
loop
l_result := replace(l_result, l_rec.var, l_rec.value);
end loop;
return l_result;
end;
$$
language plpgsql;
Then you can use it like this:
select s.id, s.sentence, replace_vars(s.sentence, to_jsonb(l)) new_sentence
from sentences s
left join logs l on l.sentenceid = s.id;
Online example
Elegance is always nice, but sometimes brute force gets it done.
with logsnn (sentenceid, var1, var2, var3,var4) as
( select sentenceid
, coalesce(var1,'')
, coalesce(var2,'')
, coalesce(var3,'')
, coalesce(var4,'')
from logs
)
select s.id
,(replace(replace(replace(replace(s.sentence
, '[var1]',l.var1)
, '[var2]',l.var2)
, '[var3]',l.var3)
, '[var4]',l.var4)
) AS sentence
from sentences s
left join logsnn l
on l.sentenceid = s.id;
If you really need the brackets on the result change the replacement settings to
'[var1]','[' || l.var1 || ']')
The answer by #JNevill is close to the same, bit I believe that one will return Null if any of var1,var2,var3, or var4 are Null. The CTE here changes Null with the empty string. Postgres does not consider the empty string the same as null.

Mutating error on an AFTER insert trigger

CREATE OR REPLACE TRIGGER TRG_INVOICE
AFTER INSERT
ON INVOICE
FOR EACH ROW
DECLARE
V_SERVICE_COST FLOAT;
V_SPARE_PART_COST FLOAT;
V_TOTAL_COST FLOAT;
V_INVOICE_DATE DATE;
V_DUEDATE DATE;
V_REQ_ID INVOICE.SERVICE_REQ_ID%TYPE;
V_INV_ID INVOICE.INVOICE_ID%TYPE;
BEGIN
V_REQ_ID := :NEW.SERVICE_REQ_ID;
V_INV_ID := :NEW.INVOICE_ID;
SELECT SUM(S.SERVICE_COST) INTO V_SERVICE_COST
FROM INVOICE I, SERVICE_REQUEST SR, SERVICE S, SERVICE_REQUEST_TYPE SRT
WHERE I.SERVICE_REQ_ID = SR.SERVICE_REQ_ID
AND SR.SERVICE_REQ_ID = SRT.SERVICE_REQ_ID
AND SRT.SERVICE_ID = S.SERVICE_ID
AND I.SERVICE_REQ_ID = V_REQ_ID;
SELECT SUM(SP.PRICE) INTO V_SPARE_PART_COST
FROM INVOICE I, SERVICE_REQUEST SR, SERVICE S, SERVICE_REQUEST_TYPE SRT,
SPARE_PART_SERVICE SRP,
SPARE_PART SP
WHERE I.SERVICE_REQ_ID = SR.SERVICE_REQ_ID
AND SR.SERVICE_REQ_ID = SRT.SERVICE_REQ_ID
AND SRT.SERVICE_ID = S.SERVICE_ID
AND S.SERVICE_ID = SRP.SERVICE_ID
AND SRP.SPARE_PART_ID = SP.SPARE_PART_ID
AND I.SERVICE_REQ_ID = V_REQ_ID;
V_TOTAL_COST := V_SERVICE_COST + V_SPARE_PART_COST;
SELECT SYSDATE INTO V_INVOICE_DATE FROM DUAL;
SELECT ADD_MONTHS(SYSDATE, 1) INTO V_DUEDATE FROM DUAL;
UPDATE INVOICE
SET COST_SERVICE_REQ = V_SERVICE_COST, COST_SPARE_PART =
V_SPARE_PART_COST,
TOTAL_BALANCE = V_TOTAL_COST, PAYMENT_DUEDATE = V_DUEDATE, INVOICE_DATE =
V_INVOICE_DATE
WHERE INVOICE_ID = V_INV_ID;
END;
I'm trying to calculate some columns after the user inserts a row.
Using the service_request_id I want to calculate the service/parts/total cost. Also, I would like to generate the creation and due dates. But, I keep getting
INVOICE is mutating, trigger/function may not see it
Not sure how the table is mutating after the insert statement.
Not sure how the table is mutating after the insert statement.
Imagine a simple table:
create table x(
x int,
my_sum int
);
and an AFTER INSERT FOR EACH ROW trigger, similar to yours, which calculates a sum of all values in the table and updates my_sum column.
Now imagine this insert statement:
insert into x( x )
select 1 as x from dual
connect by level <= 1000;
This single statement basically inserts 1000 records, each one with 1 value, see this demo: http://sqlfiddle.com/#!4/0f211/7
Since in SQL each individual statement must be ATOMIC (more on this here: Statement-Level Read Consistency, Oracle is free to perform this query in any way as long as the final result is correct (consistent). It can save records in the order of execution, maybe in reverse order, it can divide the batch into 10 threads and do it in parallel.
Since the trigger is fired individually after inserting each row, and it cannot know in advance the "final" result, then considering the above all the below results are possible depending on "internal" method choosed by Oracle to execute this query. As you see, these result do not meet the definition of consistency. And Oracle prevents this issuing mutating table error.
In other words - your assumption are bad and your design is flawed, you need to change it.
| X | MY_SUM |
|---|--------|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
...
...
or maybe :
| X | MY_SUM |
|---|--------|
| 1 | 1000 |
| 1 | 1000 |
| 1 | 1000 |
| 1 | 1000 |
| 1 | 1000 |
| 1 | 1000 |
| 1 | 1000 |
...
or maybe:
| X | MY_SUM |
|---|--------|
| 1 | 4 |
| 1 | 8 |
| 1 | 12 |
| 1 | 16 |
| 1 | 20 |
| 1 | 24 |
| 1 | 28 |
...
...

Copy and Cascade insert using PL/SQL

Given data structure:
I have the following table My_List, where Sup_ID is Primary Key
My_List
+--------+----------+-----------+
| Sup_ID | Sup_Name | Sup_Code |
+--------+----------+-----------+
| 1 | AA | 23 |
| 2 | BB | 87 |
| 3 | CC | 90 |
+--------+----------+-----------+
And the following table _MyList_details, where Buy_ID is Primary Key and Sup_ID is Foreign Key points at My_List.Sup_ID
My_List_details
+--------+--------+------------+------------+------------+
| Buy_ID | Sup_ID | Sup_Detail | Max_Amount | Min_Amount |
+--------+--------+------------+------------+------------+
| 23 | 1 | AAA | 1 | 10 |
| 33 | 2 | BBB | 11 | 20 |
| 43 | 3 | CCC | 21 | 30 |
+--------+--------+------------+------------+------------+
Finally, I have the table My_Sequence as follow:
My_Sequence
+-----+------+
| Seq | Name |
+-----+------+
| 4 | x |
| 5 | y |
| 6 | z |
+-----+------+
---------------------------------------------------
Objectives
Write PL/SQL script to:
Using a cursor, I need to copy My_List records and re-insert it with the new Sup_ID copied from My_Sequence.Seq.
I need to copy My_List_details records and re-insert them with the new Sup_ID foreign key.
------------------------------------------------------------------------------
Expected Outcome
My_List
+--------+----------+----------+
| Sup_ID | Sub_Name | Sub_Code |
+--------+----------+----------+
| 1 | AA | 23 |
| 2 | BB | 87 |
| 3 | CC | 90 |
| 4 | AA | 23 |
| 5 | BB | 87 |
| 6 | CC | 90 |
+--------+----------+----------+
My_List_details
+--------+--------+------------+------------+------------+
| Buy_ID | Sup_ID | Sub_Detail | Max_Amount | Min_Amount |
+--------+--------+------------+------------+------------+
| 23 | 1 | AAA | 1 | 10 |
| 33 | 2 | BBB | 11 | 20 |
| 43 | 3 | CCC | 21 | 30 |
| 53 | 4 | AAA | 1 | 10 |
| 63 | 5 | BBB | 11 | 20 |
| 73 | 6 | CCC | 21 | 30 |
+--------+--------+------------+------------+------------+
What I have started with is the following:
DECLARE
NEW_Sup_ID Sup_ID%type := Seq;
c_Sup_Name Sup_Name%type;
c_Sup_Code Sup_Code%type;
c_Buy_ID Buy_ID%type;
c_Sup_Detail Sup_Detail%type;
c_Max_Amount Max_Amount%type
c_My_Min_Amount Min_Amount%type
CURSOR c_My_List
IS
SELECT * FROM My_List;
CURSOR c_My_List_details
IS
SELECT * FROM My_List_details
BEGIN
FETCH c_My_List INTO NEW_Sup_ID, c_Sup_Name, c_Sup_Code;
INSERT INTO My_List;
FETCH c_My_List_details INTO c_Buy_ID, NEW_Sup_ID, c_Sup_Detail, c_Max_Amount, c_Min_Amount
INSERT INTO My_List_details
END;
/
Aside from the syntax errors, I do not see my script copy row by row and insert them to both tables accordingly. Further, the number of My_Sequence records is bigger than the number of My_List records. So what I need is, if My_List records are 50, I need the script to copy the first 50 Seq from My_Sequence.
---------------------------------------------------------------------------------
Question
How to achieve this result? I have searched and found Tom Kyte for cascade update but I am not sure if I do need to use this package, I am a bit beginner in PL/SQL and it is a bit complicated for me to utilize such a comprehensive package. Further, it's for cascade update and my case is about re-insert. I'd appreciate any help
The following Sql Statements will perform the task on the schema defined at this SqlFiddle. Note that I have changed a couple of field and table names - because they clash with Oracle terms. SqlFiddle seems to have some problems with my code, but it has been tested on another (amphibious) client which shall remain nameless.
The crucial point (As I said in my comments) is deriving a rule to map old sequence number to new. The view SEQUENCE_MAP performs this task in the queries below.
You may be disappointed by my reply because it depends upon there being the exact same number of sequence records as LIST/LIST_DETAILS, and hence it can only be run once. Your final PL/SQL can perform the necessary checks, I hope.
Hopefully it is a matter of refining the sequence_map logic to get you where you want to be.
Avoid using cursors; ideally when manipulating relational data you need to think in terms of sets of data rather than rows. This is because if you use set-thinking Oracle can do its magic in optimising, parallelising and so-on. Oracle is brilliant at scaling up - If a table is split over multiple disks, for example, it may process your request with data from the multiple disks simultaneously. If you force it into a row-by-row, procedural logic you may find that the applications you write do not scale up well.
CREATE OR REPLACE VIEW SEQUENCE_MAP AS (
SELECT OLD_SEQ, NEW_SEQ FROM
(
( SELECT ROWNUM AS RN, SUP_ID AS OLD_SEQ FROM
(SELECT SUP_ID FROM LIST ORDER BY SUP_ID) ) O
JOIN
( SELECT ROWNUM AS RN, SUP_ID AS NEW_SEQ FROM
(SELECT SEQ AS SUP_ID FROM SEQUENCE_TABLE ORDER BY SEQ) ) N
ON N.RN = O.RN
)
);
INSERT INTO LIST
(
SELECT
NEW_SEQ, SUB_NAME, SUB_CODE
FROM
SEQUENCE_MAP
JOIN LIST L ON
L.SUP_ID = SEQUENCE_MAP.OLD_SEQ
);
INSERT INTO LIST_DETAILS
(
SELECT
BUY_ID, NEW_SEQ, SUB_DETAIL, MAX_FIELD, MIN_FIELD
FROM
SEQUENCE_MAP
JOIN LIST_DETAILS L ON
L.SUP_ID = SEQUENCE_MAP.OLD_SEQ
);
I would do 2 inner loops, and search the next sequence to use.
I imagine the new buy_id is assigned via trigger using a sequence, or something equivalent, else you'll have to generate it in your code.
I have no Oracle database available to test it, so don't pay attention to syntax.
DECLARE
NEW_Sup_ID Sup_ID%type := Seq;
c_Sup_ID Sup_ID%type := Seq;
c_Sup_Name Sup_Name%type;
c_Sup_Code Sup_Code%type;
c_Buy_ID Buy_ID%type;
c_Sup_Detail Sup_Detail%type;
c_Max_Amount Max_Amount%type;
c_My_Min_Amount Min_Amount%type;
CURSOR c_My_List
IS
SELECT * FROM My_List;
CURSOR c_My_List_details
IS
SELECT * FROM My_List_details where sup_id=c_Sup_ID;
BEGIN
for c_My_List IN c_Sup_ID, c_Sup_Name, c_Sup_Code loop
select min(seq) from My_sequence into NEW_Sup_ID;
INSERT INTO My_List (sup_id,...) values (NEW_Sup_ID,...);
for c_My_List_details IN c_Buy_ID, NEW_Sup_ID, c_Sup_Detail, c_Max_Amount, c_Min_Amount loop
INSERT INTO My_List_details (sup_id, ...) values (NEW_Sup_ID,...);
end loop;
deelte from from My_sequence where seq= NEW_Sup_ID;
end loop;
commit;
END;
/

How to join table with dynamic identifier in postgres?

I have a table name table containing two columns foreign_table_name, and foreign_key.
Is it possible to write a SELECT query that would JOIN values of this table and the table which name is specified in the column foreign_table_name ?
For instance, if we know that all possible targetted foreign tables have a name field, I would like to know if I could write something that would:
SELECT table.foo, table.bar, foreign_table.name
FROM table
JOIN $foreign_table AS foreign_table
ON (foreign_table.id = table.foreign_key
$foreign_table = table.foreign_table);
Any solution using PlpgSQL is of course accepted.
Here's a simple content:
Table ``table``
------------------------------------------------
| foo | bar | foreign_table_name | foreign_key |
------------------------------------------------
| A | 1 | fruits | 8 |
| B | 2 | vegetable | 5 |
------------------------------------------------
Table ``fruit``
---------------
| id | name |
---------------
| 8 | apple |
---------------
Table ``vegetable``
----------------
| id | name |
----------------
| 5 | carrot |
----------------
The expected result table would be:
----------------------
| foo | bar | name |
----------------------
| A | 1 | apple |
| B | 2 | carrot |
----------------------
EDIT: I added the full table example in an attempt to be clearer.
It's usually way easier to do this sort of thing on the client side, but if you want it's possible with PL/PgSQL, e.g.
CREATE OR REPLACE FUNCTION dynamic_call(tblname text)
RETURNS TABLE (foo int, bar text, fname text)
AS $$
BEGIN
RETURN QUERY EXECUTE format('
SELECT t.foo, table.bar, f."name"
FROM mytable t
JOIN %I AS f ON (f.id = t.foreign_key);', tblname);
END;
$$ LANGUAGE plpgsql;
For more information, see the PL/PgSQL documentation.

SQL QUERY Error :subquery returns more than one row

I am newbie to SQL and DATABASE learning , trying to solve the following Database problem:
We have a table with two column name and marks. Write a query based on this table which returns grades like if marks if greater than 700, it will be 'A' if it is less than 700 and greater than 500, it will be 'B' OR it will be 'C'. Main point table has only two column.
Here's the query:
CREATE TABLE class (name varchar(20),marks int);
INSERT INTO class VALUES ("anu",1000),("abhi",100),("mittal",800),("chanchal",1200),("gurpreet",750),("somesh",1000),("sonia",600),("khushbu",450),("rashi",1100),("jyoti",550);
Select * FROM class;
It shows following Table:
| name | marks |
| anu | 1000 |
| abhi | 100 |
| mittal | 800 |
| chanchal | 1200 |
| gurpreet | 750 |
| somesh | 1000 |
| sonia | 600 |
| khushbu | 450 |
| rashi | 1100 |
| jyoti | 550 |
SELECT * FROM class where Grade =(SELECT CASE WHEN marks >700 THEN "A" WHEN marks<700 and marks<700 THEN "B" ELSE "C" END as GRADE FROM class);
It shows following error:
ERROR 1242 (21000): Subquery returns more than 1 row
Need help with the last command.
select name ,
CASE WHEN marks >700 THEN 'A' WHEN marks<700 and marks<700 THEN 'B' ELSE 'C' END as GRADE
from class
The above query should fulfill your need , this will display the name and the grades according to the criteria set by you.
I hope by SQL you meant Sql Server.