Skip to Main Content
  • Questions
  • Native Dynamic sql not working for first time for the given set of parameters in a procedure

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, uday.

Asked: January 21, 2020 - 12:18 pm UTC

Last updated: February 05, 2020 - 9:09 am UTC

Version: 11.2.0.4.0

Viewed 1000+ times

You Asked

create or replace  procedure tmp_insert_emp(
vempno varchar2 default null,
vename varchar2 default null,
vdname varchar2 default null)
as 
v_query varchar2(32767);
v_where varchar2(32767);
BEGIN
v_where:=' WHERE emp.deptno=dept.deptno';
IF TRIM(vempno) IS NOT NULL THEN 
V_WHERE  :=V_WHERE||' AND EMPNO='''||vempno||'''';
end if;
IF TRIM(vename) IS NOT NULL THEN 
V_WHERE  :=V_WHERE||' AND ename='''||vename||'''';
end if;
IF TRIM(vdname) IS NOT NULL THEN 
V_WHERE  :=V_WHERE||' AND dname='''||vdname||'''';
end if;
v_query :='insert into tmp_emp  select empno,ename,job, dname from emp ,dept';
execute immediate v_query||V_WHERE;
end;



Hi My procedure looks like above
when i run the procedure with a new set of parameters no rows are getting inserted
but for the second time with same set of parameters correct number of rows getting inserted
if i change new set of parameters above scenario is happening again
can you tell what is causing this kind of behavior in my procedure

exec exec tmp_insert_emp(null,null,'ACCOUNTING'); -- 0 rows inserted
exec tmp_insert_emp(null,null,'ACCOUNTING'); -- 3 rows inserted
Note:- i am unable to reproduce same scenario with above procedure



and Connor said...

We would need to see your actual code, but I will say this:

V_WHERE  :=V_WHERE||' AND ename='''||vename||'''';


is a very very very bad idea. You are opening yourself up to hacking here.

Check out this link for a much better way

https://blogs.oracle.com/oraclemagazine/on-popularity-and-natural-selection

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Updated the process using bind variables

A reader, February 03, 2020 - 3:27 pm UTC

Hi ,
Thanks for the advice
But my procedure is behaving weirdly
When I call the procedure from application for the first time it's not returning any data and second time onwards data is being populated
If I change parameters same thing is happening this behaviour is happening only in production env .
The procedure is running properly in developement environment
Chris Saxon
February 05, 2020 - 9:09 am UTC

What exactly are you doing? Show us a complete example, including:

- create table
- inserts
- procedure call

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library