SQL to Stored Procedure - oracle

I am working on a project and there is a need to write stored procedure instead of SQL query. I have never done this before and I tried now by converting the written sql to a procedure. However, I couldn't get this error free and working. Any suggestions from you folks is very helpful in fixing this..
SQL:
create or replace
PROCEDURE MS_TST_PROC AS
BEGIN
DECLARE
l_organization varchar2(40);
l_framework varchar2(10);
l_sub_category_code varchar2(20);
l_sub_category varchar2(20);
l_TST_function varchar2(20);
l_questionnaire_name varchar2(20);
l_responded_on varchar2(20);
l_overall_score number(10);
l_target_score number(10);
l_maturity number(10,2);
l_full_name varchar2(20);
cursor c_get_details
is
select
ts.organization_name,
q.framework,
q.sub_category_code,
q.sub_category,
tst.tst_function,
q.questionnaire_name,
resp.responded_on ,
resp.overall_score,
ts.target_score,
Round((resp.overall_score / ts.target_score)*100,2) as Maturity,
users.first_name || ' ' || users.last_name as full_name
into
l_organization,
l_framework,
l_sub_category_code,
l_sub_category,
l_tst_function,
l_questionnaire_name,
l_responded_on,
l_overall_score,
l_target_score,
l_maturity,
l_full_name
from MS_CMM_QUESTIONNAIRE q
INNER JOIN MS_CMM_TARGET_SCORE ts
on q.sub_category_code = ts.sub_category_code
INNER JOIN MS_CMM_CSF_FUNCTIONS tst
on tst.sub_category_code = q.sub_category_code
INNER JOIN MS_QSM_QUESTIONNAIRE qsm
on q.QUESTIONNAIRE_NAME = qsm.QUE_NAME
INNER JOIN MS_QSM_QUESTNR_RESP resp
on resp.QUESTIONNAIRE_ID = qsm.QUE_ID
and resp.applies_to_object = ts.organization_name
INNER JOIN SI_USERS_T users
on users.user_name = resp.respondent;
END MS_TST_PROC;
and compilation error says:
Error(60,1): PLS-00103: Encountered the symbol "END" when expecting one of the following: begin function pragma procedure subtype type <an identifier> <a double-quoted delimited-identifier> current cursor delete exists prior

There are a couple of issues:
You have a DECLARE statement without a subsequent BEGIN or END statement.
You have a CURSOR with an INTO clause; they cannot both be there. If the query returns a single row then just use SELECT ... INTO ... (see below), otherise, if you have multiple rows you need to process then you could use a cursor loop.
Also, it is much easier to read (and to find unmatched DECLARE/BEGIN/END statements) if you format your code and maintain proper levels of indentation.
Something like this:
CREATE PROCEDURE MS_TST_PROC
AS
l_organization MS_CMM_TARGET_SCORE.ORGANIZATION%TYPE;
l_framework MS_CMM_QUESTIONNAIRE.FRAMEWORK%TYPE;
l_sub_category_code MS_CMM_QUESTIONNAIRE.SUB_CATEGORY_CODE%TYPE;
l_sub_category MS_CMM_QUESTIONNAIRE.SUB_CATEGORY%TYPE;
l_TST_function MS_CMM_CSF_FUNCTIONS.TST_FUNCTION%TYPE;
l_questionnaire_name MS_CMM_QUESTIONNAIRE.QUESTIONNAIRE_NAME%TYPE;
l_responded_on MS_QSM_QUESTNR_RESP.RESPONDED_ON%TYPE;
l_overall_score MS_QSM_QUESTNR_RESP.OVERALL_SCORE%TYPE;
l_target_score MS_CMM_TARGET_SCORE.TARGET_SCORE%TYPE;
l_maturity number(10,2);
l_full_name varchar2(20);
BEGIN
SELECT ts.organization_name,
q.framework,
q.sub_category_code,
q.sub_category,
tst.tst_function,
q.questionnaire_name,
resp.responded_on,
resp.overall_score,
ts.target_score,
Round((resp.overall_score / ts.target_score)*100,2),
users.first_name || ' ' || users.last_name
INTO l_organization,
l_framework,
l_sub_category_code,
l_sub_category,
l_tst_function,
l_questionnaire_name,
l_responded_on,
l_overall_score,
l_target_score,
l_maturity,
l_full_name
FROM MS_CMM_QUESTIONNAIRE q
INNER JOIN MS_CMM_TARGET_SCORE ts
on q.sub_category_code = ts.sub_category_code
INNER JOIN MS_CMM_CSF_FUNCTIONS tst
on tst.sub_category_code = q.sub_category_code
INNER JOIN MS_QSM_QUESTIONNAIRE qsm
on q.QUESTIONNAIRE_NAME = qsm.QUE_NAME
INNER JOIN MS_QSM_QUESTNR_RESP resp
on resp.QUESTIONNAIRE_ID = qsm.QUE_ID
and resp.applies_to_object = ts.organization_name
INNER JOIN SI_USERS_T users
on users.user_name = resp.respondent;
-- Do something with the values.
END MS_TST_PROC;
/

Related

PL/SQL %rowtype variable declaration represents inner join

In my PL/SQL script, how do I declare JUSTIFIC_REC when it represents a join?
SELECT *
INTO JUSTIFIC_REC
FROM TABLE1 A
INNER JOIN TABLE2 B
ON A.ID_JUSTIFIC = B.ID_JUSTIFIC ;
All I want is to insert into a TABLE3 a concatenated row:
INSERT INTO MOF_OUTACCDTL_REQ VALUES(
JUSTIFIC_rec.ENTRY_COMMENTS || ' ' || JUSTIFIC_rec.DESCRIPTION );
How should the declaration of JUSTIFIC_REC be like in the beginning of my script?
If it wasn't for the INNER JOIN , I would write something like:
JUSTIFIC_rec TABLE1%ROWTYPE;
If I understood correctly you can try with cursor rowtype like this (not sure if that is what you meant by declaring your variable type for the select with joins):
set serveroutput on;
declare
cursor cur is
SELECT ENTRY_COMMENTS, DESCRIPTION
FROM TABLE1 A
INNER JOIN TABLE2 B
ON A.ID_JUSTIFIC = B.ID_JUSTIFIC ;
justific_rec cur%ROWTYPE;
begin
open cur;
loop
fetch cur into justific_rec;
exit when cur%notfound;
dbms_output.put_line(justific_rec.entry_comments || ' ' || justific_rec.description);
end loop;
close cur;
end;
Answer to your question is itself in your question. You have to use the %row type
tow type attribute can be any of the below type:
rowtype_attribute :=
{cursor_name | cursor_variable_name | table_name} % ROWTYPE
cursor_name:-
An explicit cursor previously declared within the current scope.
cursor_variable_name:-
A PL/SQL strongly typed cursor variable, previously declared within the current scope.
table_name:-
A database table or view that must be accessible when the declaration is elaborated.
So code will looks like
DECLARE
CURSOR c1 IS
SELECT * FROM TABLE1 A
INNER JOIN TABLE2 B
ON A.ID_JUSTIFIC = B.ID_JUSTIFIC ;
justific_rec c1%ROWTYPE;
BEGIN
open c1;
loop
fetch c1 into justific_rec;
exit when c1%notfound;
INSERT INTO MOF_OUTACCDTL_REQ VALUES(
JUSTIFIC_rec.ENTRY_COMMENTS || ' ' || JUSTIFIC_rec.DESCRIPTION );
end loop;
close c1;
END;
/
You need to use BULK COLLECT INTO
SELECT *
BULK COLLECT INTO JUSTIFIC_REC
FROM TABLE1 A
INNER JOIN TABLE2 B
ON A.ID_JUSTIFIC = B.ID_JUSTIFIC ;
The JUSTIFIC_REC is needed to be TABLE type with appropriate columns
If all you're wanting to do is insert into a table based on a select statement, then there's no need for PL/SQL (by which I mean there's no need to open a cursor, fetch a row, process the row and then move on to the next row) - that's row-by-row aka slow-by-slow processing.
Instead, you can do this all in a single insert statement, e.g.:
INSERT INTO mof_outaccdtl_rec (<column being inserted into>) -- please always list the columns being inserted into; this avoids issues with your code when someone adds a column to the table.
SELECT entry_comments || ' ' || description -- please alias your columns! How do we know which table each column came from?
FROM table1 a
inner join table2 b on a.id_justific = b.id_justific;
If you wanted to embed this insert statement in PL/SQL, all you need to do is add a begin/end around it, like so:
begin
INSERT INTO mof_outaccdtl_rec (<column being inserted into>) -- please always list the columns being inserted into; this avoids issues with your code when someone adds a column to the table.
SELECT entry_comments || ' ' || description -- please alias your columns! How do we know which table each column came from?
FROM table1 a
inner join table2 b on a.id_justific = b.id_justific;
end;
/
This is the preferred solution when working with databases - think in sets (where possible) not procedurally (aka row-by-row processing). It is easier to maintain, the code is simpler to read and write, and it'll be more performant since you're not having to switch between PL/SQL and SQL several times with each row.
Context switching is bad for performance - think in terms of a bath full of water - is it quicker to empty the bath with a spoon (row-by-row processing), with a jug (batched rows - by - batched rows) or by pulling the plug (set-based)?

Trying to assign a single value from a query to a variable... what am i doing wrong?

I am trying to to set a variable (v_flag_id) to the result of a query. I've been looking online at examples and it seems like my formatting/syntax is correct. What am i doing wrong? Thanks in advance.
create or replace PROCEDURE RUN_AGG
is
declare
v_Flag_id Number := select flag_id from flag where flag_tx = 'Processed / Calculated';
CURSOR hours IS
SELECT distinct(HR) as RHR
, submission_value_id
from (
select
v.DATA_DATE,
v.HR,
sv.submission_value_id
from value v
inner join submission_value sv on sv.value_id = v.value_id
where sv.SUBMISSION_VALUE_ID NOT IN (
SELECT SUBMISSION_VALUE_ID FROM VALUE_FLAG WHERE VALUE_FLAG.FLAG_ID = v_Flag_id
);
BEGIN
OPEN hours;
LOOP
FETCH hours into l_hr;
EXIT WHEN hours%NOTFOUND;
AGG_HOURLY_REG_FINAL(l_hr.RHR);
END LOOP;
CLOSE hours;
END RUN_AGG;
The error that I am receiving is as follows:
Error(6,1): PLS-00103: Encountered the symbol "DECLARE" when expecting one
of the following: begin function pragma procedure subtype type <an
identifier> <a double-quoted delimited-identifier> current cursor delete
exists prior external language
Use the following :
CREATE OR REPLACE PROCEDURE RUN_AGG IS
l_rhr VARCHAR2 (100);
l_sub_vl_id VARCHAR2 (100);
CURSOR hours is
SELECT distinct (HR) as RHR, submission_value_id
FROM (SELECT v.DATA_DATE, v.HR, sv.submission_value_id
FROM value_ v
INNER JOIN submission_value sv
ON (sv.value_id = v.value_id)
WHERE sv.SUBMISSION_VALUE_ID NOT IN
(SELECT SUBMISSION_VALUE_ID
FROM VALUE_FLAG
WHERE VALUE_FLAG.FLAG_ID in
(SELECT flag_id
FROM flag
WHERE flag_tx = 'Processed / Calculated')));
BEGIN
OPEN hours;
LOOP
FETCH hours INTO l_rhr, l_sub_vl_id;
EXIT WHEN hours%NOTFOUND;
AGG_HOURLY_REG_FINAL(l_rhr);
END LOOP;
CLOSE hours;
END RUN_AGG;
remove declare
take select flag_id into v_Flag_id from flag where flag_tx =
'Processed / Calculated'; sql in hours cursor's select. So, remove v_Flag_id variable.
return two variables for two columns l_rhr and l_sub_vl_id.
I replaced the name of the table value with value_, since it's a
reserved keyword for oracle.

Oracle FOR Loop inside a FOR loop

Here is my code. Please forgive me for not putting variables in declaration section as the editor was giving me tough time in formatting it before I could submit my issue.
I want the result variable (v_Var) to have value printed as
v_ID = :NEW.ID;
v_NAME = :NEW.NAME;
v_ENTITY_ID = :NEW.ENTITY_ID;
BUT, it is getting printed as
v_ID = :NEW.ID;
v_ID = :NEW.ID;
v_NAME = :NEW.NAME;
v_ENTITY_ID = :NEW.ENTITY_ID;
Since the table TEMP_TRG_CONSTRNT has 2 rows, it is working for v_ID also for two times.
I know the issue is with external FOR loop but I am not sure how to handle it.
DECLARE
CURSOR c1 IS
SELECT NAME, OCCUR_COUNT FROM IFMS_SYSTEMCONFIGURATION.TEMP_TRG_CONSTRNT;
BEGIN
v_TableName := 'MyTable';
EXECUTE IMMEDIATE 'TRUNCATE TABLE IFMS_SYSTEMCONFIGURATION.TEMP_TRG_CONSTRNT';
INSERT INTO IFMS_SYSTEMCONFIGURATION.TEMP_TRG_CONSTRNT (NAME, OCCUR_COUNT)
SELECT A.FKN, COUNT(A.FKN) AS OCCUR_COUNT FROM
(
SELECT A.CONSTRAINT_NAME AS FKN FROM ALL_CONSTRAINTS A
INNER JOIN ALL_CONS_COLUMNS B
ON A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
WHERE A.CONSTRAINT_TYPE IN ('P', 'U') AND A.TABLE_NAME = 'MyTable'
)A
GROUP BY A.FKN;
--FOR CONSTR_NAME IN (SELECT NAME FROM IFMS_SYSTEMCONFIGURATION.TEMP_TRG_CONSTRNT)
FOR CONSTR_NAME IN c1
LOOP
--SELECT NAME, OCCUR_COUNT INTO v_Constr_Name, v_Index_Count FROM TEMP_TRG_CONSTRNT WHERE NAME = CONSTR_NAME.NAME;
FOR COL_NAME IN (SELECT COLUMN_NAME FROM ALL_CONS_COLUMNS WHERE CONSTRAINT_NAME = CONSTR_NAME.NAME)
LOOP
v_Var := v_Var || 'v_' || COL_NAME.COLUMN_NAME || ' = :NEW.' || COL_NAME.COLUMN_NAME || ';' || CHR(13);
END LOOP;
DBMS_OUTPUT.PUT_LINE(v_Var);
END LOOP;
END;
There could be a couple of things causing your results:
There are tables in different schemas with the same name (you're missing a join on owner between the two tables)
There could be more than one constraint on the same table.
In addition to those, you've also managed to recreate a Nested Loop join, by doing the nested looping. In general, this is a bad idea - what if a Hash Join was more performant? You will have effectively hobbled Oracle by using your nested cursor for loops. At the very least, you could join your two cursors in a single sql statement before looping through it.
However, it looks like you're trying to generate a list of variables without having to type them. You can do this in a single SQL statement - no need for PL/SQL, like so:
SELECT DISTINCT con.constraint_name,
con.owner,
con.table_name,
col.column_name,
'v_'||col.column_name||' := :NEW.'||col.column_name||';'
FROM all_constraints con
inner JOIN all_cons_columns col ON con.constraint_name = col.constraint_name
AND con.owner = col.owner
AND con.constraint_type IN ('P', 'U')
--AND con.owner = 'SOME_OWNER' -- uncomment out and put in the correct owner name, esp if your table exists in more than one owner.
AND con.table_name = 'YOUR_TABLE'
ORDER BY con.owner, con.table_name;
Note that I've included extra columns, so that you can work out why you're getting the results you're getting, just in case that doesn't match what you're expecting to see. I included the DISTINCT keyword to take care of the case where you have multiple constraints returned for a single owner.table.
If you want to generate a list of variables for multiple tables at once, you might want to use the aggregate listagg function on the above query (meaning you could remove the DISTINCT) with a delimiter of CHR(10).

Oracle cursor with variable columns/tables/criteria

I need to open a cursor while table name, columns and where clause are varying. The table name etc will be passed as parameter. For example
CURSOR batch_cur
IS
SELECT a.col_1, b.col_1
FROM table_1 a inner join table_2 b
ON a.col_2 = b.col_2
WHERE a.col_3 = 123
Here, projected columns, table names, join criteria and where clause will be passed as parameters. Once opened, i need to loop through and process each fetched record.
You need to use dynamic SQL something like this:
procedure dynamic_proc
( p_table_1 varchar2
, p_table_2 varchar2
, p_value number
)
is
batch_cur sys_refcursor;
begin
open batch_cur for
'select a.col_1, b.col_1
from ' || p_table_1 || ' a inner join || ' p_table_2 || ' b
on a.col_2 = b.col_2
where a.col_3 = :bind_value1';
using p_value;
-- Now fetch data from batch_cur...
end;
Note the use of a bind variable for the data value - very important if you will re-use this many times with different values.
From your question i guess you need a dynamic cursor. Oracle provides REFCURSOR for dynamic sql statements. Since your query will be built dynamically you need a refcursor to do that.
create procedure SP_REF_CHECK(v_col1 number,v_col2 date,v_tab1 number,v_var1 char,v_var2 varchar2)
is
Ref_cur is REF CURSOR;
My_cur Ref_cur;
My_type Table_name%rowtype;
stmt varchar2(500);
begin
stmt:='select :1,:2 from :3 where :4=:5';
open My_cur for stmt using v_col1,v_col2,v_tab1,v_var1,v_var2;
loop
fetch My_cur into My_type;
//do some processing //
exit when My_cur%notfound;
end loop;
close My_cur;
end;
Check this link for more http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/11_dynam.htm

Oracle Stored Procedure Call from iSQL PLUS Invalid Identifier

I have created a procedure using the following code using iSQL Plus on Firefox. The procedure compiles successfully.
create or replace procedure get_staff (
product_no in varchar2,
o_cursor out sys_refcursor)
is
begin
open o_cursor for
'select sr.name, sr.bonus from sales_staff sr inner join product p on p.sales_staff_id = sr.staff_id where product_no = ' || product_no ;
end;
I am trying to call this procedure using the following code
var rc refcursor
exec get_staff('A56',:rc)
print rc
I get the following error.
ERROR at line 1:
ORA-00904: "A56": invalid identifier
ORA-06512: at "AA2850.GET_STAFF", line 6
ORA-06512: at line 1
ERROR:
ORA-24338: statement handle not executed
SP2-0625: Error printing variable "rc"
in the case you have, there's no need for dynamic sql:
open o_cursor for
select sr.name, sr.bonus
from sales_staff sr
inner join product p
on p.sales_staff_id = sr.staff_id
where p.product_no = product_no;
if you were using dynamic SQL then ideally you would in most cases want to bind:
open o_cursor for
'select sr.name, sr.bonus
from sales_staff sr
inner join product p
on p.sales_staff_id = sr.staff_id
where p.product_no = :b1' using product_no;
failing that (edge cases, sometimes you want to avoid bind variables for skewed data), varchar2s need enclosing in quotes:
open o_cursor for
'select sr.name, sr.bonus
from sales_staff sr
inner join product p
on p.sales_staff_id = sr.staff_id
where p.product_no = ''' ||product_no||'''';
but you should escape single quotes and validate that product_no has no semi colons etc (i.e. careful of SQL injection)

Resources