Executing SQL via Oracle Stored Procedure passing variables - sql

I created the following Stored Procedure in Oracle:
create or replace
PROCEDURE APPUSERCT
(
PROJNAME IN VARCHAR2
, WHEREDATE IN VARCHAR2 ,
cnt OUT long
) AS
BEGIN
select count(Distinct UPPER(field1)) into cnt from bs_log where application_name=PROJNAME and field1 is not null and log_type='info' || WHEREDATE;
END APPUSERCT;
In my php page WHEREDATE is set as:
$whereDate=" and (TO_DATE(created_on,'mm/dd/yyyy HH24:MI:SS')>= TO_DATE('".$startDate."','mm/dd/yyyy') AND TO_DATE(created_on,'mm/dd/yyyy HH24:MI:SS')<= TO_DATE('".$endDate."','mm/dd/yyyy'))";
I then Bind the parameters and values and call the SP:
$sql = 'BEGIN APPUSERCT(:projName,:whereDate,:cnt); END;';
$result = oci_parse($dbconn, $sql);
oci_bind_by_name($result,':cnt',$totalRowCount,32);
oci_bind_by_name($result,':projName',$projName,32);
oci_bind_by_name($result,':whereDate',$whereDate,200);
oci_execute($result);
If no date range is entered on the php page by the user, then the WHEREDATE is blank in the SP and the SQL runs without any range or any additional syntax appended to the end of it in the Store Procedure (SP).
When the user enters a date range on the php page then the WHEREDATE param becomes:
and (TO_DATE(created_on,'mm/dd/yyyy HH24:MI:SS')>=TO_DATE('05/01/2015','mm/dd/yyyy') AND TO_DATE(created_on,'mm/dd/yyyy HH24:MI:SS')<=TO_DATE('05/07/2015','mm/dd/yyyy'))
and it is appended to the end of the SQL in the SP. But whenever this happens my php page always returns 0 count from the SQL executed. No error, just 0 count.
If I try running the SQL directly in Oracle it's:
select count(Distinct UPPER(field1)) as cnt from bs_log where application_name='Myweather' and field1 is not null and log_type='info' and (TO_DATE(created_on,'mm/dd/yyyy HH24:MI:SS')>= TO_DATE('05/01/2015','mm/dd/yyyy') AND TO_DATE(created_on,'mm/dd/yyyy HH24:MI:SS')<= TO_DATE('05/07/2015','mm/dd/yyyy'))
and I get results. I get a count back. But when calling it through the procedure I get 0. Can anyone see why?
Thanks!

Well, a couple of problems show up.
First, I suggest that you change the declaration of the cnt parameter from LONG to NUMBER. LONG is not a numeric type in Oracle; instead, it's a type of LOB whose use is deprecated. If you really want to return a LOB use either BLOB or CLOB, whichever is appropriate.
Second, you can't pass in a character string containing part of a WHERE clause (the WHEREDATE parameter) and concatenate it to the end of an SQL statement. In this case you were contatenating the text in WHEREDATE to the string literal info, which I suspect is not what you had in mind. You should probably be using dynamic SQL, in a manner similar to the following:
create or replace PROCEDURE APPUSERCT(PROJNAME IN VARCHAR2,
WHEREDATE IN VARCHAR2,
cnt OUT NUMBER)
AS
strSql_text VARCHAR2(32767) := 'select count(Distinct UPPER(field1)) ' ||
' from bs_log where application_name=''' || PROJNAME ||
''' and field1 is not null and ' ||
' log_type=''info'' ' || WHEREDATE;
csr SYS_REFCURSOR;
BEGIN
OPEN csr FOR strSql_text;
FETCH csr INTO cnt;
CLOSE csr;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('APPUSERCT - exception : ' || SQLCODE || ' (' ||
SQLERRM || ')');
RAISE;
END APPUSERCT;
So you build up the SQL statement as a text string, including your addition to the WHERE clause, then use the OPEN statement to open a cursor for that statement. Then the cursor is fetched, placing the result into cnt, then the cursor is closed, and finally the routine exits. I've included a default EXCEPTION handler as well - always a good idea in any routine.

Related

Pass SQL string to oracle stored procedure and get results with execute immediate

I am trying to pass in a SQL string to a stored procedure and using EXECUTE IMMEDIATE to return the results. Something like this:
CREATE PROCEDURE P360_RCT_COUNT (sqlString IN VARCHAR2)
AS
BEGIN
EXECUTE IMMEDIATE sqlString;
END;
/
I am not sure how to accomplish it. With the above, when I execute the SP using the command below, I get an error:
EXECUTE P360_RCT_COUNT 'SELECT COUNT(DISTINCT ENTITY_ID),ADDR_COUNTY FROM P360_V_RCT_COUNT GROUP BY ADDR_COUNTY';
The error is: ORA-06550: line 1, column 22:
PLS-00103: Encountered the symbol "SELECT COUNT(ENTITY_ID),ADDR_COUNTY
FROM P360_V_RCT_COUNT GROUP " when expecting one of the following:
:= . ( # % ; The symbol ":=" was substituted for "SELECT
COUNT(DISTINCT ENTITY_ID),ADDR_COUNTY FROM P360_V_RCT_COUNT GROUP " to
continue.
Basically I am building a SQL string in a system and need to pass it in to the SP and get the results back to the system. I am relatively new to stored procedures in Oracle.
The easiest way to work with a result set is sys_refcursor. This can be used quite easily with JDBC or ODBC.
Your procedure would look like this:
CREATE PROCEDURE P360_RCT_COUNT (
sqlString IN VARCHAR2
, p_result_set out sys_refcursor)
AS
BEGIN
open p_result_set for sqlString;
END;
/
Obviously the precise details of how you call it will vary according to your client. But in SQL*Plus it would be:
var rc refcursor
exec P360_RCT_COUNT( 'SELECT COUNT(DISTINCT ENTITY_ID),ADDR_COUNTY FROM P360_V_RCT_COUNT GROUP BY ADDR_COUNTY', :rc);
print rc
To return lists of values in a OUT parameter you need to decide the type(s) to use.
Say, for example, you have to return some varchar2 and some date lists, you could use something like this:
create or replace type tabOfVarchar2 is table of varchar2(100);
create or replace type tabOfDates is table of date;
create or replace procedure testProc(pString IN varchar2,
pOutVarchar1 OUT tabOfVarchar2,
pOutVarchar2 OUT tabOfVarchar2,
pOutVarchar3 OUT tabOfVarchar2,
pOutDates OUT tabOfDates
) is
begin
execute immediate pString
bulk collect into pOutVarchar1, pOutVarchar2, pOutVarchar3, pOutDates;
end;
This is way you can test this procedure:
declare
v1 tabOfVarchar2 ;
v2 tabOfVarchar2;
v3 tabOfVarchar2;
d1 tabOfDates ;
vSQL varchar2(100) := 'select ''a'', ''b'', ''c'', sysdate from dual';
begin
testProc(vSQL, v1, v2, v3, d1);
--
for i in v1.first .. v1.last loop
dbms_output.put_line(v1(i) || '/' || v2(i) || '/' || v3(i) || '/' || to_char(d1(i), 'dd/mm/yyyy'));
end loop;
end;
which gives:
a/b/c/14/04/2017
This only works with queries that give exactly a fixed number of columns, of known types.

HANA - Passing string variable into WHERE IN() clause in SQL script

Lets suppose I have some SQL script in a scripted calculation view that takes a single value input parameter and generates a string of multiple inputs for an input parameter in another calculation view.
BEGIN
declare paramStr clob;
params = select foo
from bar
where bar.id = :IP_ID;
select '''' || string_agg(foo, ''', ''') || ''''
into paramStr
from :params;
var_out = select *
from "_SYS_BIC"."somepackage/MULTIPLE_IP_VIEW"(PLACEHOLDER."$$IP_IDS$$" => :paramStr);
END
This works as expected. However, if I change the var_out query and try to use the variable in a where clause
BEGIN
...
var_out = select *
from "_SYS_BIC"."somepackage/MULTIPLE_IP_VIEW"
where "IP_IDS" in(:paramStr);
END
the view will activate, but I get no results from the query. No runtime errors, just an empty result set. When I manually pass in the values to the WHERE IN() clause, everything works fine. It seems like an elementary problem to have, but I can't seem to get it to work. I have even tried using char(39) rather than '''' in my concatenation expression, but no banana :(
Ok, so what you are doing here is trying to make the statement dynamic.
For the IN condition, you seem to hope that once you have filled paramStr it would be handled as a set of parameters.
That's not the case at all.
Let's go with your example from the comment: paramStr = ' 'ip1','ip2' '
What happens, when the paramStr gets filled into your code is this:
var_out = select *
from "_SYS_BIC"."somepackage/MULTIPLE_IP_VIEW"
where "IP_IDS" in(' ''ip1'',''ip2'' ');
So, instead of looking for records that match IP_DS = 'ip1' or IP_DS = 'ip2' you are literally looking for records that match IP_DS = ' 'ip1','ip2' '.
One way to work around this is to use the APPLY_FILTER() function.
var_out = select *
from "_SYS_BIC"."somepackage/MULTIPLE_IP_VIEW";
filterStr = ' "IP_IDS" in (''ip1'',''ip2'') ';
var_out_filt = APPLY_FILTER(:var_out, :filterStr) ;
I've written about that some time ago: "On multiple mistakes with IN conditions".
Also, have a look at the documentation for APPLY_FILTER.
The SAP note “2315085 – Query with Multi-Value Parameter on Scripted Calculation View Fails with Incorrect Syntax Error“ actually showcases the APPLY_FILTER() approach that failed when I first tried it.
It also presents an UDF_IN_LIST function to convert a long varchar string with array of items from input parameter to a usable in-list predicate.
Unfortunately, couldn't make it work in sps11 rev 111.03 despite some parameter available (SAP Note 2457876 :to convert error into warning for string length overflow) - (range 3) string is too long exception
then ALTER SYSTEM ALTER CONFIGURATION ('indexserver.ini', 'System') set ('sqlscript', 'typecheck_procedure_input_param') = 'false' WITH RECONFIGURE;
-recompile the Calc View
then
select * from :var_tempout where OBJECT_ID in (select I_LIST from "BWOBJDES"."CROSS_AREA::UDF_INLIST_P"(:in_objectids,','));
invalid number exception - invalid number
But taking the scripting out of the function makes it work...
For this SPS 11 level APPLY_FILTER seems to be the only workaround. And it is really hard to say what would be the rev on SPS 12 to go in order to have it.
FUNCTION "BWOBJDES"."CROSS_AREA::UDF_INLIST_P"(str_input nvarchar(5000),
delimiter nvarchar(10))
RETURNS table ( I_LIST INTEGER ) LANGUAGE SQLSCRIPT SQL SECURITY INVOKER AS
/********* Begin Function Script ************/
BEGIN
DECLARE cnt int;
DECLARE temp_input nvarchar(128);
DECLARE slice NVARCHAR(10) ARRAY;
temp_input := :str_input;
cnt := 1;
WHILE length(temp_input) > 0 DO
if instr(temp_input, delimiter) > 0 then
slice[:cnt] := substr_before(temp_input,delimiter);
temp_input := substr_after(temp_input,delimiter);
cnt := :cnt + 1;
else
slice[:cnt] := temp_input;
break;
end if;
END WHILE;
tab2 = UNNEST(:slice) AS (I_LIST);
return select I_LIST from :tab2;
END;
CREATE PROCEDURE "MY_SCRIPTED_CV/proc"( IN numbers NVARCHAR(5000), OUT
var_out
MY_TABLE_TYPE ) language sqlscript sql security definer reads sql data with
result view
"MY_SCRIPTED_CV" as
/********* Begin Procedure Script ************/
BEGIN
-- not working
--var_out = select * from MY_TABLE where NUMBER in (select I_LIST from
--UDF_INLIST_P(:numbers,','));
-- working
DECLARE cnt int;
DECLARE temp_input nvarchar(128);
DECLARE slice NVARCHAR(13) ARRAY;
DECLARE delimiter VARCHAR := ',';
temp_input := replace(:numbers, char(39), '');
cnt := 1;
WHILE length(temp_input) > 0 DO
if instr(temp_input, delimiter) > 0 then
slice[:cnt] := substr_before(temp_input,delimiter);
temp_input := substr_after(temp_input,delimiter);
cnt := :cnt + 1;
else
slice[:cnt] := temp_input;
break;
end if;
END WHILE;
l_numbers = UNNEST(:slice) AS (NUMBER);
var_out=
SELECT *
FROM MAIN AS MA
INNER JOIN l_numbers as LN
ON MAIN.NUMBER = LN.NUMBER
END;
I know, this is a quite old thread but nevertheless my findings based what I read in here from Jenova might be interesting for others. Thatswhy I am writing them down.
I was faced with the same problem. Users can sent multiple entrie in an input parameter in a calc view I have to optimize. Unluckily I run into the same problem like Jenova and others before. And, no, imho this is not about dynamic view execution or dynamic sql, but about processing in lists in a clean way in a scripted calc view or table function if they are send in an input parameter.
Lars' proposal to use APPLY_FILTER is not applicable in my case, since I cannot use a complex statement in the APPLY_FILTER function itself. I have to materialize the whole amount of data in the select, which result I can assign to APPLY_FILTER and then execute the filtering. I want to see the filtering applied in the first step not after materializing data which is not appearing in the result of the filter application.
So I used a hdbtablefunction to create a function performing the parameter string cleanup and the transformation into an array and afterwards it is returning the result of the UNNEST function.
Since the result of the function is a table it can be used as a table inside the scripted view or tablefunction - in joins, subselects and so on.
This way I am able to process user input lists as expected, fast and with much less resource consumption.
FUNCTION "_SYS_BIC"."package1::transparam" (ip_string NVARCHAR(500) )
RETURNS table ( "PARAMETER" nvarchar(100))
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER AS
v_test varchar(1000);
IP_DELIMITER VARCHAR(1) := ',';
v_out VARCHAR(100):='';
v_count INTEGER:=1;
v_substr VARCHAR(1000):='';
v_substr2 VARCHAR(1000):='';
id INTEGER array;
val VARCHAR(100) array;
BEGIN
--
v_substr:=:ip_string;
v_substr := REPLACE(:v_substr, '''', '');
v_substr := REPLACE(:v_substr, ' ', '');
while(LOCATE (:v_substr, :ip_delimiter) > 0 ) do
-- find value
v_out := SUBSTR(v_substr, 0, LOCATE (:v_substr, :ip_delimiter) - 1 );
-- out to output
val[v_count]:=v_out;
-- increment counter
v_count:=:v_count+1;
-- new substring for search
v_substr2 := SUBSTR(:v_substr, LOCATE (:v_substr, :ip_delimiter) + 1, LENGTH(:v_substr));
v_substr := v_substr2;
END while;
IF(LOCATE (:v_substr, :ip_delimiter) = 0 AND LENGTH(:v_substr) > 0) THEN
-- no delimiter in string
val[v_count]:=v_substr;
END IF;
-- format output as tables
rst = unnest(:VAL) AS ("PARAMETER");
RETURN SELECT * FROM :rst;
END;
can be called like
select * from "package1.transparam"('''BLU'',''BLA''')
returning table with two lines
PARAMETER
---------
BLU
BLA
The most comprehensive explanation is here:
https://blogs.sap.com/2019/01/17/passing-multi-value-input-parameter-from-calculation-view-to-table-function-in-sap-hana-step-by-step-guide/
Creating custom function splitting string into multiple values
Then inner/left outer join can be used to filter.

dynamic sql selection in nested select

Let's say that I have a tables tasks, projects, and work_items, all of which have a column fields containing a json object of custom values.
Now lets say I want to write a function to query an arbitrary table for its field names.
CREATE OR REPLACE FUNCTION getFieldNames(varchar) RETURNS varchar[] AS
$BODY$
DECLARE
fieldNames varchar[];
BEGIN
fieldNames := ARRAY(SELECT DISTINCT fieldName FROM
(EXECUTE 'SELECT json_object_keys(fields) AS fieldName FROM '
|| quote_ident($1)
) AS derivedFields
);
RETURN fieldNames;
END
$BODY$
LANGUAGE 'plpgsql';
This however errors out with:
ERROR: syntax error at or near "'SELECT json_object_keys(fields) AS fieldName FROM'"
LINE 8: (EXECUTE 'SELECT json_object_keys(fields) AS fieldNa..
The Nested select itself is sound as I verified by replacing the execute with
(SELECT json_object_keys(fields) AS fieldName
FROM tasks
)
and receiving correct results.
What is wrong with my code?
The EXECUTE statement does not return a relation that you can use as a sub-query. Instead, if it returns anything at all, it populates a variable or a single row through the INTO clause. The latter obviously does not match your requirement so you are stuck with the first. A more elegant solution is to move the EXECUTE statement outwards:
EXECUTE
'SELECT array_agg(DISTINCT fields) FROM ' ||
'(SELECT json_object_keys(fields) AS fields FROM ' || quote_ident($1) || ') AS x'
INTO fieldNames;
The worst issue is wrong position of EXECUTE statement. It is a PLpgSQL statement and then it cannot be placed in any SQL expression.

Error in Parameters of Stored Procedure when Dynamic SQL is used

I am using Oracle Sql Developer to write a Stored Proc, which accepts a list of values separated by "," (dynamic sql) and use this variable in "in" clause to fire a query from a table.
But i am ending up with an error at
#p_case_nbr varchar2(100),
Error(4,5): PLS-00103: Encountered the symbol "#" when expecting one of the following: current delete exists prior
The SP used:
create or replace
procedure TEST_PROC
(
#p_case_nbr varchar2(100),
p_out_case_nbr out varchar2
)
as
cursor test_cur is
select t.COLUMN1
from test_table t
where t.column1 in (#p_case_nbr);
test_cur_line test_cur%ROWTYPE;
begin
p_out_case_nbr := null;
open test_cur;
LOOP
FETCH test_cur INTO test_cur_line;
EXIT WHEN test_cur%NOTFOUND;
p_out_case_nbr := p_out_case_nbr || ' ' || test_cur_line.COLUMN1;
dbms_output.put_line(test_cur_line.COLUMN1);
end loop;
close test_cur;
dbms_output.put_line('Final Value ' || p_out_case_nbr);
dbms_output.put_line('SP Completed Succesfully');
end;
In ORACLE no need of giving # before varibles
Just try to remove the # from #p_case_nbr where ever specified and try once again
and also no need of specifying the size of the parameter like #p_case_nbr varchar2(100)
just give #p_case_nbr varchar

Executing SQL Function using toad

I am very new to DB. I am java developer and nothing to do with SQL Functions.
But now I am in a situation where I need to check whether an sql function is getting executed properly on db or not
CREATE OR REPLACE FUNCTION RATELIMIT_OWN.Get_Logs ( p_yyyymm VARCHAR2, p_numec NUMBER )
RETURN LOG_RECORD_TABLE PIPELINED IS
TYPE ref0 IS REF CURSOR;
cur0 ref0;
out_rec LOG_RECORD := log_record(NULL,NULL,NULL);
BEGIN
OPEN cur0 FOR
'SELECT eventid, errormsg, create_date from logs partition (LOGS_P' || p_yyyymm || ') where numec=:1'
USING p_numec;
LOOP
FETCH cur0 INTO out_rec.eventid, out_rec.msg, out_rec.create_date;
EXIT WHEN cur0%NOTFOUND;
PIPE ROW(out_rec);
END LOOP;
CLOSE cur0;
RETURN;
END Get_Logs;
/
How to execute this sql function in toad. I want to see the results like normal Select query output
To check a table valued function please try:
select * FROM table(RATELIMIT_OWN.Get_Logs('a', 1));
FOE EXECUTING THE FUNCTION
SELECT RATELIMIT_OWN.Get_Logs(....,...) FROM DUAL ;
AND
ORA-00904: MEAN COLUMN NAME IS NOT VALID PLSS CHECK THE COLUMN NAME
Try:
select RATELIMIT_OWN.Get_Logs(...) from dual;