Oracle SQL - Alternative for dynamic query - sql

I have a procedure (see below) which is using dynamic query. I wanted to rewrite this procedure with out using dynamic query. How do I write the conditions below?
PROCEDURE DemoProcedure(p_firstname IN VARCHAR2,
p_lastname IN VARCHAR2,
p_phone IN VARCHAR2
o_Cursor OUT t_Cursor) IS
SQLString VARCHAR2(4000);
BEGIN
SQLString :=
'SELECT * FROM
SCHEMA.TABLENAME_a A
INNER JOIN SCHEMA.TABLENAME_b B
ON A.ID = B.ID
WHERE
A.TYPE = 1 ';
IF p_firstname IS NOT NULL THEN
SQLString := SQLString || ' and UPPER(A.FIRST_NAME) like UPPER( ''' || p_firstname || ''')';
END IF;
IF p_lastname IS NOT NULL THEN
SQLString := SQLString || ' and UPPER(A.LAST_NAME) like UPPER( ''' || p_lastname || ''')';
END IF;
IF p_phone IS NOT NULL THEN
SQLString := SQLString || ' and UPPER(A.PHONE) = ''' ||
p_phone || '''';
END IF;
SQLString := SQLString || ' order by a.id ';
OPEN o_Cursor FOR SQLString;
END DemoProcedure;

It looks like you just want
OPEN o_cursor
FOR SELECT ...
WHERE A.TYPE = 1
AND (p_firstname IS NULL or upper(a.first_name) = upper(p_firstname))
AND (p_lastname IS NULL or upper(a.last_name) = upper(p_lastname))
AND (p_phone IS NULL or upper(a.phone) = p_phone)
ORDER BY a.id
I'm not sure why you'd want to bother upper-casing a phone number-- do you have character data in a phone number?

Different way writing the same SQL as #JustinCave suggested -
OPEN o_cursor
FOR SELECT ...
WHERE A.TYPE = 1
AND upper(a.first_name) = nvl(upper(p_firstname), upper(a.first_name))
AND upper(a.last_name) = nvl(upper(p_lastname),upper(a.last_name))
AND upper(a.phone) = nvl(p_phone,upper(a.phone))
ORDER BY a.id

Related

How can i turn this pl/sql into a procedure

I had to write this query for an assignement. So we have a database and we are pulling information from it, this is going to work with some back end c# eventually. Is there anything i can do , knowing im going to reuse this, in order to make it better and more adaptable when the day comes when i have to connect it all.
set serveroutput on
DECLARE
LV_DATE HVK_RESERVATION.RESERVATION_START_DATE%TYPE;
LV_SERV VARCHAR(100);
CURSOR LCUR_RES IS
SELECT *
FROM HVK_RESERVATION R
INNER JOIN HVK_PET_RESERVATION PR
ON R.RESERVATION_NUMBER = PR.RES_RESERVATION_NUMBER
INNER JOIN HVK_PET P
ON P.PET_NUMBER = PR.PET_PET_NUMBER
INNER JOIN HVK_OWNER OW
ON OW.OWNER_NUMBER = P.OWN_OWNER_NUMBER
WHERE R.RESERVATION_START_DATE < LV_DATE
AND R.RESERVATION_END_DATE > LV_DATE;
CURSOR LCUR_SERVICE(PET_RES_NUM NUMBER) IS
SELECT *
FROM HVK_SERVICE S
INNER JOIN HVK_PET_RESERVATION_SERVICE PRS
ON PRS.SERV_SERVICE_NUMBER = S.SERVICE_NUMBER
AND PRS.PR_PET_RES_NUMBER = PET_RES_NUM;
BEGIN
LV_DATE := TO_DATE('&logdate', 'yy-mm-dd');
DBMS_OUTPUT.PUT_LINE('Kennel log for ' || '' || LV_DATE);
DBMS_OUTPUT.PUT_LINE('-------------------------------');
FOR I IN LCUR_RES LOOP
DBMS_OUTPUT.PUT_LINE('Run:' || '' || I.RUN_RUN_NUMBER || ' ' ||
'Pet: ' || '' || I.PET_NAME || ' ' ||
I.OWNER_LAST_NAME || ' Pet Reservation: ' || '' ||
I.PET_RES_NUMBER);
DBMS_OUTPUT.PUT_LINE('Reservation start/end ' || ' ' ||
I.RESERVATION_START_DATE || ' ' ||
I.RESERVATION_END_DATE);
DBMS_OUTPUT.PUT('Services : ');
FOR X IN LCUR_SERVICE(I.PET_RES_NUMBER) LOOP
DBMS_OUTPUT.PUT(X.SERVICE_DESCRIPTION || ' ');
END LOOP;
DBMS_OUTPUT.PUT_LINE('');
FOR LREC_LOG IN (SELECT *
FROM HVK_KENNEL_LOG KL
WHERE KL.PR_PET_RES_NUMBER = I.PET_RES_NUMBER
) LOOP
DBMS_OUTPUT.PUT_LINE('Notes: ' || '' ||
LREC_LOG.KENNEL_LOG_SEQUENCE_NUMBER || ' ' ||
'Log Note: ' || '' || LREC_LOG.KENNEL_LOG_NOTES);
END LOOP;
DBMS_OUTPUT.PUT_LINE(' ');
END LOOP;
END;
It it supposed to output the run number , reservation number , pet name , and any relate notes.
you can replace DECLARE with CREATE OR REPLACE PROCEDURE my_proc(in_logdate in date) IS.
in that case my_proc will be the name of your procedure.
you should also use a parameter instead of &logdate
so e.g. parameter name in_logdate of type date
...
LV_DATE := in_logdate;
...

Teradata Stored Procedure variables

I'm trying to create a stored procedure to create all possible combination of a table with itself. For now, I got this code, but it produces the following error:
Syntax error: expected something between the word 'A' and the integer '2'
Code:
CREATE MULTISET TABLE PRUEBA
(
CAMPO VARCHAR(10)
);
INSERT INTO PRUEBA VALUES('A');
INSERT INTO PRUEBA VALUES('B');
INSERT INTO PRUEBA VALUES('C');
REPLACE PROCEDURE TEST()
BEGIN
DECLARE a VARCHAR(255);
DECLARE b VARCHAR(225);
DECLARE qry VARCHAR(255);
DECLARE i INT;
DECLARE n INT;
SET a = 'SELECT * FROM PRUEBA A1 ';
SET b = ' WHERE ';
SET n = 3;
SET i = 1;
WHILE i < n DO
BEGIN
CASE i
WHEN 1 THEN
SET qry = a;
WHEN 2 THEN
SET a = a || 'CROSS JOIN PRUEBA A' || i ; -- Error in this part.
SET b = b || 'A' || (i-1) || '.CAMPO < A' || i || '.CAMPO';
SET qry = a || b;
ELSE
SET a = a || 'CROSS JOIN PRUEBA A' || i ;
SET b = b || 'AND A' || (i-1) || '.CAMPO < A' || i || '.CAMPO';
SET qry = a || b;
END CASE;
SET i = i + 1;
END;
END WHILE;
EXECUTE IMMEDIATE qry;
END;
CALL TEST();
I'd join the 'i' variable to create multiple alias for all cross tables.
Your i variable is an INTEGER. Try casting it as a VARCHAR() when you do your concatenations:
SET a = a || 'CROSS JOIN PRUEBA A' || CAST(i AS VARCHAR(2)) ; -- Error in this part.
SET b = b || 'A' || CAST((i-1) AS VARCHAR(2)) || '.CAMPO < A' ||
CAST(i AS VARCHAR(2)) || '.CAMPO';
You'll have to do this in the subsequent ELSE block as well.
Use explicit CAST or TRIM to avoid the leading blanks generated by implicit cast from INTEGER to VARCHAR. And you need to use a dynamic cursor to return the result of the SELECT to the caller.
REPLACE PROCEDURE TEST()
DYNAMIC RESULT SETS 1 --Allow returning data to caller
BEGIN
DECLARE a VARCHAR(255);
DECLARE b VARCHAR(225);
DECLARE qry VARCHAR(4096);
DECLARE i INT;
DECLARE n INT;
DECLARE csr1 CURSOR WITH RETURN FOR stmt1; --Declare a dynamic cursor
SET a = 'SELECT * FROM PRUEBA A1 ';
SET b = ' WHERE ';
SET n = 3;
SET i = 1;
WHILE i < n DO
BEGIN
CASE i
WHEN 1 THEN
SET qry = a;
WHEN 2 THEN
SET a = a || 'CROSS JOIN PRUEBA A' || TRIM(i) ;
SET b = b || 'A' || TRIM(i-1) || '.CAMPO < A' || TRIM(i) || '.CAMPO';
SET qry = a || b;
ELSE
SET a = a || 'CROSS JOIN PRUEBA A' || TRIM(i) ;
SET b = b || 'AND A' || TRIM(i-1) || '.CAMPO < A' || TRIM(i) || '.CAMPO';
SET qry = a || b;
END CASE;
SET i = i + 1;
END;
END WHILE;
PREPARE stmt1 FROM qry; --Prepare a dynamic SQL statement for the cursor
OPEN csr1; --Execute the SELECT statement
--Leave a WITH RETURN cursor open to return the result set
END;
if you're using bteq you might have to write the procedure into a file and load it with .compile directive.
once you are loggen in and supposing the file is /tmp/stored_procedure.sql
compile it like this:
.compile file='/tmp/stored_procedure.sql';

Pass column name as a parameter

I need to pass a column name from front end to back end in my code. i'm using c# with oracle and when i pass the column name as a parameter, it gives an error and it's because the column name is used as a string in here and i need to know how to fix this. here is my code,
PROCEDURE PR_GETCLIENTCONTRACTDATA(INSTRFIELD IN VARCHAR2,INSTRCONTRACTNO IN VARCHAR2,CUR_OUTPUT OUT T_CURSOR)--ADDED BY DIDULA 25/10/2017
IS
BEGIN
OPEN CUR_OUTPUT FOR
SELECT c.con_no,
DECODE (a.clm_cori,
'1', a.clm_cltitle || ' ' || a.clm_initialsfull || ' '
|| a.clm_name,
a.clm_name
) cliname,
a.clm_code,
( a.clm_permaddline1
|| '|'
|| a.clm_permaddline2
|| '|'
|| COALESCE (a.clm_permaddline3, a.clm_permaddline4)
|| '|'
|| NULLIF ((a.clm_permaddline4),
COALESCE (a.clm_permaddline3, a.clm_permaddline4)
)
) address
FROM leaseinfo.tblcontracts c, corpinfo.tblclientmain a
WHERE a.clm_code = c.con_clmcode
AND INSTRFIELD = INSTRCONTRACTNO; ***here INSTRFIELD is the column name
that i need to pass***
END PR_GETCLIENTCONTRACTDATA;
Whitelist the column names:
PROCEDURE PR_GETCLIENTCONTRACTDATA(
INSTRFIELD IN VARCHAR2,
INSTRCONTRACTNO IN VARCHAR2,
CUR_OUTPUT OUT T_CURSOR
)
IS
BEGIN
OPEN CUR_OUTPUT FOR
SELECT -- your select clauses
FROM leaseinfo.tblcontracts c,
INNER JOIN corpinfo.tblclientmain a -- ANSI join syntax
ON a.clm_code = c.con_clmcode
WHERE CASE INSTRFIELD
WHEN 'COLUMNA' THEN ColumnA
WHEN 'COLUMNB' THEN ColumnB
WHEN 'COLUMNC' THEN ColumnC
END = INSTRCONTRACTNO;
END PR_GETCLIENTCONTRACTDATA;
/
When you use OPEN cur FOR ... you can pass a string, i.e.
PROCEDURE PR_GETCLIENTCONTRACTDATA(INSTRFIELD IN VARCHAR2,INSTRCONTRACTNO IN VARCHAR2,CUR_OUTPUT OUT T_CURSOR)
IS
BEGIN
OPEN CUR_OUTPUT FOR
'SELECT c.con_no,
DECODE (a.clm_cori,
''1'', a.clm_cltitle || '' '' || a.clm_initialsfull || '' ''
|| a.clm_name,
a.clm_name
) cliname,
a.clm_code,
( a.clm_permaddline1
|| ''|''
|| a.clm_permaddline2
|| ''|''
|| COALESCE (a.clm_permaddline3, a.clm_permaddline4)
|| ''|''
|| NULLIF ((a.clm_permaddline4),
COALESCE (a.clm_permaddline3, a.clm_permaddline4)
)
) address
FROM leaseinfo.tblcontracts c
JOIN corpinfo.tblclientmain a ON a.clm_code = c.con_clmcode
WHERE '||DBMS_ASSERT.SIMPLE_SQL_NAME(INSTRFIELD)||' = :INSTRCONTRACTNO)'
USING INSTRCONTRACTNO;
END PR_GETCLIENTCONTRACTDATA;

Finding specific data in Oracle Tables

I needed to find a value for a column in my oracle database but i don't know which
table or column it's stored in
How can I search for a specific or like %% data as I do in
select * from SYS.dba_source
is there a table like that
Column Name ID Data Type Null? Comments
OWNER 1 VARCHAR2 (30 Byte) Y
NAME 2 VARCHAR2 (30 Byte) Y Name of the object
TYPE 3 VARCHAR2 (12 Byte) Y
Type of the object:
"TYPE", "TYPE BODY", "PROCEDURE", "FUNCTION",
"PACKAGE", "PACKAGE BODY" or "JAVA SOURCE"
LINE 4 NUMBER Y Line number of this line of source
TEXT 5 VARCHAR2 (4000 Byte) Y Source text
LINK: pl/sq to find any data in a schema
Imagine, there are a few tables in your schema and you want to find a specific value in all columns within these tables. Ideally, there would be an sql function like
select * from * where any(column) = 'value';
Unfortunately, there is no such function.
However, a PL/SQL function can be written that does that. The following function iterates over all character columns in all tables of the current schema and tries to find val in them.
create or replace function find_in_schema(val varchar2)
return varchar2 is
v_old_table user_tab_columns.table_name%type;
v_where Varchar2(4000);
v_first_col boolean := true;
type rc is ref cursor;
c rc;
v_rowid varchar2(20);
begin
for r in (
select
t.*
from
user_tab_cols t, user_all_tables a
where t.table_name = a.table_name
and t.data_type like '%CHAR%'
order by t.table_name) loop
if v_old_table is null then
v_old_table := r.table_name;
end if;
if v_old_table <> r.table_name then
v_first_col := true;
-- dbms_output.put_line('searching ' || v_old_table);
open c for 'select rowid from "' || v_old_table || '" ' || v_where;
fetch c into v_rowid;
loop
exit when c%notfound;
dbms_output.put_line(' rowid: ' || v_rowid || ' in ' || v_old_table);
fetch c into v_rowid;
end loop;
v_old_table := r.table_name;
end if;
if v_first_col then
v_where := ' where ' || r.column_name || ' like ''%' || val || '%''';
v_first_col := false;
else
v_where := v_where || ' or ' || r.column_name || ' like ''%' || val || '%''';
end if;
end loop;
return 'Success';
end;

pl sql and dynamic sql

I am trying to create some dynamic sql using the following code block
firstSqlStatement := true;
updateText := 'UPDATE T_EMPLOYEES SET ';
if FIRSTNAME IS NOT NULL and FIRSTNAME > 0 THEN
updateText:=updateText || ' firstName=' || FIRSTNAME || ' ';
firstSqlStatement := false;
end if;
if MIDDLENAME IS NOT NULL and length(MIDDLENAME) > 0 THEN
if firstSqlStatement = false THEN
updateText:=updateText || ',';
end if;
updateText:=updateText || ' middleName=' || MIDDLENAME || ' ';
firstSqlStatement := false;
end if;
updateText:=updateText
|| ' where upper(id)=upper(' || ID ||');';
DBMS_OUTPUT.put_line(updateText);
EXECUTE IMMEDIATE updateText;
The statement never executes properly as there are missing single quotes around values.
Any ideas what i can do to make this small example work or is there any better way of doing this?
firstSqlStatement := true;
updateText := 'UPDATE T_EMPLOYEES SET ';
if FIRSTNAME IS NOT NULL and FIRSTNAME > 0 THEN
updateText:=updateText || ' firstName=''' || FIRSTNAME || ''' ';
firstSqlStatement := false;
end if;
if MIDDLENAME IS NOT NULL and length(MIDDLENAME) > 0 THEN
if firstSqlStatement = false THEN
updateText:=updateText || ',';
end if;
updateText:=updateText || ' middleName=''' || MIDDLENAME || ''' ';
firstSqlStatement := false;
end if;
updateText:=updateText || ' where upper(id)=upper(' || ID || ');';
DBMS_OUTPUT.put_line(updateText);
EXECUTE IMMEDIATE updateText;
use '''
Maybe you can do it this way.
declare
ll_employee_id number := 10;
lv_firstname varchar2(30) := 'Thomas';
lv_middlename varchar2(30) := null;
begin
update t_employees
set firstname = decode(lv_firstname, null, firstname, lv_firstname),
middlename = decode(lv_middlename, null, middlename, lv_middlename)
where employee_id = ll_employee_id;
end;
DECLARE
my_error exception;
sql_stmt VARCHAR2 (500);
v_char_field VARCHAR2 (500);
v_number_field NUMBER;
v_stmt_number NUMBER;
BEGIN
sql_stmt := 'UPDATE TABLE';
IF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION FIELD
THEN
sql_stmt := sql_stmt || 'field_1 = :1';
v_stmt_number := 1;
ELSIF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION FIELD
THEN
sql_stmt := sql_stmt || 'field_2 = :1';
v_stmt_number := 2;
ELSE
DBMS_OUTPUT.put_line ('Field unmanaged');
RAISE my_error;
END IF;
IF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION TYPE FIELD
THEN
EXECUTE IMMEDIATE sql_stmt USING v_char_field;
ELSIF 1 = 1 -- REPLACE WITH CONDITION FOR SELECTION TYPE FIELD
THEN
EXECUTE IMMEDIATE sql_stmt USING v_number_field;
ELSE
DBMS_OUTPUT.put_line ('Type Field unmanaged');
RAISE my_error;
END IF;
DBMS_OUTPUT.PUT_LINE ('STATEMENT NUMBER : ' || v_stmt_number);
DBMS_OUTPUT.PUT_LINE ('TOTAL RECORD UPDATE : ' || SQL%ROWCOUNT);
EXCEPTION
WHEN my_error
THEN
NULL;
WHEN OTHERS
THEN
DBMS_OUTPUT.PUT_LINE ('ERROR :' || SQLERRM);
END;
You can use multiple selections to compose your statement for selection fields to be updated and for the type.