Query in Pl/Sql

Hi All,
We have senario in which two sql statements are running in large volume.
So we decided to write those statements with execute immedate bcz to take the advantage of bind variables save parsing time in each execution.
for e.g
1st Approach
IF cond =1 THEN
execute immediate 'select sal from emp where empno = :1' into l_sal using p_empno;
ELSE
execute immediate 'select comm from emp where comm = :1' into l_sal using p_empno;
END IF;
OR
2nd Approach
IF cond =1 THEN
SELECT sal
INTO l_sal
FROM emp
WHERE empno = p_empno;
ELSE
SELECT comm
INTO l_sal
FROM emp
WHERE empno = p_empno;
END IF;
We are using database 10g.
Please suggest what would be the better approach and why?

Hi,
Bear in mind, Static SQL is anytime better then Dynamic SQL.
It will make your code easy to read, easy to maintain and also better performant.
Till date that is true for any Oracle DB version (Unless tehre are exceptions that i am not aware of).
Good thing about your Dynamic SQL is you are using Bind Variables, so anytime you need to use it keep up that practice.
Dynamic SQL should be used only when there is no scope to use Static SQL.
Cheers,
Bhushan

Similar Messages

  • Query help in sql commands

    using apex 4.1 i'm entering the following query in the sql command window and I keep getting a pop-up for Entering Bind Variable. I'm not using bind variables though, anyone else see this issue before?
    SELECT A.FIRST,A.LAST,A.COMPANY AS CNAME,
    J.TOT_MAN_HOURS,
    J.ACREAGE,
    W.NUM_WORKERS,
    W.START_DT
    FROM EW_ACCOUNTS A, EW_WORK_ORDER W, EW_JOBS J
    WHERE A.ID = J.ACCT_ID
    AND J.JOB_ID = W.JOB_ID
    AND W.START_DT >= SYSDATE
    AND W.START_DT < SYSDATE+1
    ORDER BY W.START_DT

    I tried that and it didn't seem to help either.
    Funny though, if I write a new query against just one of the tables and write out each column name. it works. If I use the * instead of writing each column name, I have the same issue.
    This is in apex.appshosting.com free demo environment. I sent them an email asking about it and they told me it was a code issue and they don't support the demo environment.

  • Query in pl/sql oracle

    Hi All!
    I want to write following type of query in PL/SQL
    How can I write one which will work.
    <B>
    SELECT count(1) INTO v_count2 from TRJ_TRAN_REJ_T a and PEU_PUR_ENRL_UNT_T b
    where a.TRJ_CVRG_PER_DATE IN (b.PEU_EFF_DATE AND b.PEU_END_DATE) AND
    a.purik = b.purik AND a.peuik = b.peuik
    <B>
    Above query is not working correctly. Any changes?? DATE stored in database is like 01/01/2001
    v_count2 is NUMBER variable declared in PL?SQL.
    SA

    You don't need to use a PL/SQL, a simple SQL will suffice. I guess you could write it as a function?
    I think your SQL was wrong so I took the liberty of fixing it for you. You seperate tables with commas in a FROM clause, not AND.
    Anyway, on the lines of a SQL Statement you can do the following.
    SELECT     count(1) AS mycount
    FROM     TRJ_TRAN_REJ_T a,
         PEU_PUR_ENRL_UNT_T b
    WHERE     a.TRJ_CVRG_PER_DATE IN (b.PEU_EFF_DATE AND b.PEU_END_DATE)
    AND     a.purik = b.purik
    AND     a.peuik = b.peuik
    Connection conn = DriverManager.getConnection(URL, username, password);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery( your sql);
    while ( rs.next() )
         int mycount = rs.getInt("mycount");
    close stuff down here

  • Query in PL/SQL Help

    Hi All!
    I want to write following type of query in PL/SQL
    How can I write one which will work.
    SELECT count(1) INTO v_count2 from TRJ_TRAN_REJ_T a and PEU_PUR_ENRL_UNT_T b
    where a.TRJ_CVRG_PER_DATE IN (b.PEU_EFF_DATE AND b.PEU_END_DATE) AND
    a.purik = b.purik AND a.peuik = b.peuik
    Above query is not working correctly. Any changes?? DATE stored in database is like 01/01/2001
    v_count2 is NUMBER variable declared in PL?SQL.
    SA

    I'd also watch out for the TIME part of the date matching, best to do a TRUNC on them, but make sure also [purik] and [peuik] are indexed. This is the format I use for a select. Some parts were removed but you get the idea.
    --[START]
    --[SELECT]
    SELECT
    --/*+ choose */
    /*+ RULE */
    --/*+ first_rows */
    --/*+ all_rows */
    count(1)          --[C1]
    --[INTO]
    INTO
    v_count2          --[V1]
    --[FROM]
    FROM
    trj_tran_rej_t T1,
    peu_pur_enrl_unt_t T2
    --[WHERE]
    WHERE
    TRUNC(T1.trj_cvrg_per_date) = TRUNC(T2.peu_eff_date)
    OR
    TRUNC(T1.trj_cvrg_per_date) = TRUNC(T2.peu_end_date)
    AND
    T1.purik = T2.purik
    AND
    T1.peuik = T2.peuik
    --[ABORT]
    AND 1=1;
    --[END]
    Tyler Durden

  • Wrong query in pl/sql

    Good Morning,
    i have a string containing a query in pl/sql :
    description varchar2(100) := 'select adeia_id||description,adeia_id from mis_adeia where plafon=1';
    which selects adeia_id and description fron a table and displays them together, but i want to seperate adeia_id and description with a blank or a dot, so i change the string and make it like:
    description varchar2(100) := 'select adeia_id||' || ' ' || 'description,adeia_id from mis_adeia where plafon=1';
    am i doing something wrong?
    thanks for reading.

    thank you peter but it doesn't work. i tried it. the string i pass it as argument in the create_group_from_query function in forms builder, and when i use double quots it gives me the error, that cannot create the group! i don't know what is the fault.

  • Query in PL/SQL code is slower

    I have a very strange issue within my development database, I'm using Oracle 10g.
    I created a query to read some data from a large collection of tables -OFDM tables- I have tested and tuned the performance of the query from (PL/SQL Developer 7 ), it takes only 2 minutes to finish but when I use the same query as a cursor in a database procedure it consume a lot of time around 15 min to get the data.
    Your help is appreciated

    [url http://groups.google.de/group/comp.databases.oracle.server/browse_frm/thread/df893cf9be9b2451/54f9cf0e937d7158?hl=de&tvc=1&q=%22Beautified%22+code+runs+slower#54f9cf0e937d7158]Recently somebody complained about slow performance after code was beatified in PL SQL Developer, after recompilation without flag "Add Debug Information" it run faster...
    (just a guess)
    Best regards
    Maxim

  • Re: How to converting from PL/SQL query to T-SQL query

    How to converting from PL/SQL query to T-SQL query... Its Urgent

    Download the
    SQL Server Migration Assistant for Oracle.  It will convert whole Oracle databases, or single queries or PL/SQL stored procedures.
    With caution that If your database is using Collation which is case sensitive SSMA will not work.SSMA doesnt guarantees 100% for conversion of Queries/stored proc /database if it fails to do so for some queries you will have to do it manually.
    But you can try
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • Data discrepancy between Webi Report and same Query fired on SQL Server 2k5

    Hi ,
    We are facing an issue in BO XI R2.
    We need to run a Webi report in which negative values for forecasting data for year 2011 and 2012 should be displayed.
    When we are running this report for negative values, we are getting message u2018There is no data corresponding to this queryu2019.
    Then we tried executing the same query on Database. Here at db level we got the correct required result.
    So now we are not able to find the reason for data discrepancy .
    Why the same query generated by Webi is providing correct data when fired on reporting database and not when running the Webi Report.
    Checklist we have gone through for this troubleshooting is-
    -Connections of Universe (Is universe pointing to same database or not)
    -Any filter condition present at universe level and at report level.
    Could anyone please help on this.
    Regards,
    Vaibhav

    Vaibhav,
    Have you tried the following when you are in WebI: go under the Edit Query panel, click on the "SQL" icon, and review the query that is getting generated?  At this point you can also click on the "copy" option, then paste this query into your SQL application analyzer and run to see what results are generated.  To me, it sounds like the portion trying to generate the "minus" sign might be getting tripped up causing the disconnect....
    Thanks,
    John

  • Crosstab query using pure SQL only

    Hi all,
    Found a lot of threads on crosstab, but none seems to address what I need. I need to perform crosstab query using pure SQL only & the number of columns are dynamic. From a query, I obtained the below table:
    Name Date Amount
    Alex 2005-06-10 1000
    Alex 2005-06-20 1000
    Alex 2005-07-10 1000
    Alex 2005-07-20 1000
    Alex 2005-08-10 1000
    Alex 2005-08-20 1000
    John 2005-06-10 2000
    John 2005-06-20 2000
    John 2005-07-10 2000
    John 2005-07-20 2000
    John 2005-08-10 2000
    John 2005-08-20 2000
    And I need to transform it into:
    Name 06-2005 07-2005 08-2005
    Alex 2000 2000 2000
    John 4000 4000 4000
    Reason for the columns being dynamic is because they'll be a limit on the date ranges to select the data from. I'd have a lower & upper bound date say June-2005 to August-2005, which explains how I got the data from the above table.
    Please advise.
    Thanks!

    Hi,
    I couldn't resist the intellectual challenge of a pure SQL solution for a pivot table with a dynamic number of columns. As Laurent pointed out, a SQL query can only have a fixed number of columns. You can fake a dynamic number of columns, though, by selecting a single column containing data at fixed positions.
    <br>
    <br>
    If it were me, I'd use a PL/SQL solution, but if you must have a pure SQL solution, here is an admittedly gruesome one. It shows the sum of all EMP salaries per department over a date range defined by start and end date parameters (which I've hardcoded for simplicity). Perhaps some of the techniques demonstrated may help you in your situation.
    <br>
    <br>
    set echo off
    set heading on
    set linesize 100
    <br>
    select version from v$instance ;
    <br>
    set heading off
    <br>
    column sort_order noprint
    column sal_sums format a80
    <br>
    select -- header row
      1        as sort_order,
      'DEPTNO' as DEPTNO ,
      sys_connect_by_path
        ( rpad
            ( to_char(month_column),
              10
          ' | '
        ) as sal_sums
    from
        select
          add_months( first_month, level - 1 ) as month_column
        from
          ( select
              date '1981-01-01' as first_month,
              date '1981-03-01' as last_month,
              months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
            from dual
        connect by level < total_months + 1
      ) months
    where
      connect_by_isleaf = 1
    connect by
      month_column = add_months( prior month_column, 1 )
    start with
      month_column = date '1981-01-01'
    union all
    select -- data rows
      2 as sort_order,
      deptno,
      sys_connect_by_path( sum_sal, ' | ' ) sal_sums
    from
      select
        dept_months.deptno,
        dept_months.month_column,
        rpad( to_char( nvl( sum( emp.sal ), 0 ) ), 10 ) sum_sal
      from
          select
            dept.deptno,
            reporting_months.month_column
          from
            dept,
            ( select
                add_months( first_month, level - 1 ) as month_column
              from
                ( select
                    date '1981-01-01' as first_month,
                    date '1981-03-01' as last_month,
                    months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
                  from
                    dual
              connect by level < total_months + 1
            ) reporting_months
        ) dept_months,
        emp
      where
        dept_months.deptno = emp.deptno (+) and
        dept_months.month_column = trunc( emp.hiredate (+), 'MONTH' )
      group by
        dept_months.deptno,
        dept_months.month_column
    ) dept_months_sal
    where
      month_column = date '1981-03-01'
    connect by
      deptno = prior deptno and
      month_column = add_months( prior month_column, 1 )
    start with
      month_column = date '1981-01-01'
    order by
      1, 2
    <br>
    VERSION
    10.1.0.3.0
    <br>
    DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01
    10          | 0          | 0          | 0
    20          | 0          | 0          | 0
    30          | 0          | 2850       | 0
    40          | 0          | 0          | 0
    <br>
    Now, if we substitute '1981-03-01' with '1981-06-01', we see 7 columns instead of 4
    <br>
    DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01   | 81-04-01   | 81-05-01   | 81-06-01
    10          | 0          | 0          | 0          | 0          | 0          | 2450
    20          | 0          | 0          | 0          | 2975       | 0          | 0
    30          | 0          | 2850       | 0          | 0          | 2850       | 0
    40          | 0          | 0          | 0          | 0          | 0          | 0
    <br>To understand the solution, start by running the innermost subquery by itself and then work your way outward.

  • Edit query results in SQL worksheet

    I can't edit query results in SQL worksheet, I not found any options to "ON" this. I use SQL Developer 2.1.1.64.

    You can't edit results in the worksheet. It's an accepted feature request with no scheduled date. In the mean time you have to go to the table or write an update statement.

  • NVARCHAR (MAX) TO PRINT DYNAMIC SQL QUERY TO A SQL FILE

    Hi 
    I have a requirement where i need to write an SP which would construct a huge query using dynamic SQL and save the Dynamic query to a file. 
    The Dynamic SQL Variable I am using as @NVARCHAR(MAX) but since the query being built is large (>4000 characters), I am not able to select it into a table. PRINT @SQL prints the whole query but SELECT @SQL prints only upto 4000 characterrs. 
    And I need to save this huge dynamix sql to a file using the SP.
    Any thoughts as to how i can achieve this?
    Rajiv

    This is a know problem with dynamic SQL nvarchar(max) concatenation.
    See below for correct assembly of large SQL strings:
    CREATE table #temp(qry nvarchar(max));
    declare @cmd nvarchar(max);
    SELECT @cmd=CONCAT(CONVERT(nvarchar(max),N'SELECT '),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),N'FROM SYS.TABLES'));
    insert into #temp SELECT @cmd;
    select * from #temp;
    select len(qry), datalength(qry) from #temp;
    -- 16022 32044
    drop table #temp;
    Dynamic SQL:  http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Transalate JPQL query to be SQL

    I'm using toplink. I wonder if there is tool to translate toplink JPQL query to be SQL in developer? what I'm looking for is I can type in a JPQL query, IDE will be able to show me the translated SQL. is this can be done in jdeveloper?
    Thanks

    Dear Friends,
    I have done the same thing. We r using PI 7.1.
    I have Sync Proxy ->  Syn JDBC . I tried to execute a simple query at the JDBC adapter by sending it through *access*  field in the XML structure.
    This is the input
    <?xml version="1.0" encoding="UTF-8" ?>
    - <ns0:CoilNoReceive xmlns:ns0="urn:essar-com:production:shearslitpoconfirm">
    - <stmt>
    - <TABLENAME action="SQL_QUERY">
      <access>SELECT coil_no,PARTS_ACT FROM P_INV where fac_index <> 6 and fac_index <>7 and rownum<5</access>
      </TABLENAME>
      </stmt>
      </ns0:CoilNoReceive>
    I am getting this error msg..
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    - <!--  Inbound Message
      -->
    - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
      <SAP:Category>XIAdapterFramework</SAP:Category>
      <SAP:Code area="MESSAGE">GENERAL</SAP:Code>
      <SAP:P1 />
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText>com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error 'java.sql.SQLException: ORA-00900: invalid SQL statement ' executing service raw2sql with SQL statement '<?xml version="1.0" encoding="UTF-8"?> <ns0:CoilNoReceive xmlns:ns0="urn:essar-com:production:shearslitpoconfirm"><stmt><TABLENAME action="SQL_QUERY"><access>SELECT coil_no,PARTS_ACT FROM P_INV where fac_index <> 6 and fac_index<>7 and rownum<5</access></TABLENAME></stmt></ns0:CoilNoReceive>'</SAP:AdditionalText>
      <SAP:Stack />
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    What could be the problem. Reply ASAP.
    Thanks
    K. Ramesh

  • Visual query  builder in SQL developer ...

    hi
    Thank you for reading my post
    when we can expect a visual query builder in sql Developer ?
    also , how i can make an auto increment field in SQL develoepr ?
    Thanks

    I can't answer your first question.. but the second has been hashed over a few times. In short, there are no auto-increment fields in Oracle. Instead there are sequences which are more complicated to use, but much more versitile.
    Auto increment trigger
    Auto Increment
    Eric

  • Can not query PQH_BUDGET_DETAILS in SQL*Plus

    Hi!
    I can see the Positions in the Forms-Mask within EBS.
    I want to write a concurrent Programm which queries some data form the positions-table.
    If i klick on "Help > Diagnostics > Examine" and select "system.last_query" i can see, that the data comes from a view called: "PQH_POS_BUDGETS_V".
    But if i try to query this view in SQL*Plus, it is empty.
    So i had a look at how this view is build, and i found, that the base tables should be PQH_BUDGETS and PQH_BUDGET_DETAILS.
    How can i query the position_id in PQH_BUDGET_DETAILS in a concurrent program or an self-writen BI Publisher Report?
    If i try to query in SQL*Plus it's empty.
    Who can help me with this issue?
    Thank you for your help!
    Best regards,
    Thomas

    Hi!
    Thats great!
    Thank you very much!
    Best regards,
    Thomas

  • SqlDeveloper Query = Fast, PL/SQL = Slow

    I've got a nagging problem that is driving me crazy. Database is 11.1.0.7 and SQLDeveloper is 1.5.1 with the same behavior in 3.0.03.
    Often I will develop a complex query in SQLDeveloper and get it tuned to a point where performance is great. However when I take that query and put it in a PL/SQL procedure with dynamic SQL the performance takes a nose dive. This happens when taking a query to an Apex report as well. I use bind variables in my queries in SQLDeveloper as well as Apex/PLSQL.
    If I run an explain plan in SQLDeveloper it is often identical to the plan for the query in the pl/sql environment (seen through tkprof), yet the sqldeveloper query window is always faster.
    The difference in speed is remarkable, my current "problem" query is runs in 71 seconds inside a PL/SQL stored procedure using dynamic sql with bind variables. If I print that query out and copy paste the query in to a SQLDeveloper sql window (worksheet?), the exact same query prompts me for the bind variable values and then runs in 0.07 seconds. Just to make sure the rows aren't caching, if I run the stored procedure version again it still takes 71+ seconds.
    If I hard code values in the PL/SQL query instead of using bind variables, the stored procedure runs as fast as SQLDeveloper, 0.07 seconds.
    I originally posted a similar problem over in the Apex forum and there we suspected the issue might be related to the 11g optimizer using bind variable peeking. SLOW report performance with bind variable
    Ultimately, the goal is to have predictable results when taking a query from SQLDeveloper to PL/SQL.
    Are there any SQLDeveloper developers out there that can confirm that "bind variable" syntax in SQL Developer is not using bind variables, but is instead rewriting the query with hard coded values in query strings?

    mcallister wrote:
    I've got a nagging problem that is driving me crazy. Database is 11.1.0.7 and SQLDeveloper is 1.5.1 with the same behavior in 3.0.03.
    when I take that query and put it in a PL/SQL procedure with dynamic SQL the performance takes a nose diveThat's one of the reasons not to use dynamic SQL - tuning the resulting queries is very difficult.
    Is the dynamic SQL necessary? If you are only using bind variables it probably is not necessary. If you are swapping WHERE clause predicates in and out through program logic then predicting performance will be very hard (or using different column or table names too)
    When I must use dynamic SQL I find a useful technique is to create a debugging table with a CLOB into which I can insert the generated SQL code for later reference. That code can be used for both debugging (looking for syntax errors) and tuning. I also find it very, very useful to write the dynamic SQL with proper formatting and linefeeds so it is immediately readable on inspection
    Are there any SQLDeveloper developers out there that can confirm that "bind variable" syntax in SQL Developer is not using bind variables, but is instead rewriting the query with hard coded values in query strings?You can see if query rewrites are taking place by using the NO_QUERY_TRANSFORMATION hint and seeing if the execution plan changes while tuning. To a lesser degree you can examine execution plans from V$SQL_PLAN to look for signs of changes like predicates you didn't code but this is also very hard

  • Query running on sql commands prompt not running on report region

    Hi All,
    Facing a weird issue now. I have written a report query which is running absolutely fine in sql command prompt but when i trying to run this as a report it is just processing and the report is not loading. What could be the reason behing this?
    Thanks in Advance
    Regards

    Hi,
    With no other information about the problem is hard to know what's happening. If you could at least provide us with the query then I think it would be easier for us to help you.
    Regards,
    Sergio

Maybe you are looking for