Parsing and rewriting an SQL query

Hi all,
I need to rewrite bits of a valid PL/SQL query. In order to do so, I need semantic information about the query, such as "what are the table names columns are being selected from" or "do aggregate functions in a select provide column alias in order to use the query in +CREATE TABLE AS+ ...".
Is it possible to somehow "ask" the Oracle parser for those bits of semantic info? I am using 9i.
E.g.
select X.ID, Y.NAME, SUM(ABS(Y.VALUE))
from
TABLE_X X,
(select NAME, VALUE from TABLE_Z where DATE_STR = '20090101') Y
where
will become
select X.ID, Y.NAME, SUM(ABS(Y.VALUE)) COL1
from
TABLE_X prefix. X,
(select NAME, VALUE from prefix. TABLE_Z where DATE_STR = '20090101') Y
where
...

Thanks for your answers (which, unfortunately, do not give much hope)!
+..so unfortunately you won't be able to use the 11g method introduced here (Anyhow still undocumented!).+
Yes, that's very disappointing. I actually added the "has to be 9i compatible" remark after I found out the XML dump does not work on our servers - and read the manual page to realize why that's the case.
I think you'd need to write your own, which will be extremely difficult and hard to maintain.*
There is a BNF grammar of PL/SQL (homebrew, apparently - so no guarantees): http://www.antlr.org/grammar/1107752678378/PLSQLGrammar.g
Now, if I only knew practical stuff about lexers and parsers and abstract syntax trees...

Similar Messages

  • Parse User Pasted Text and use in SQL query

    I am trying to take some user pasted text (typically would come from Excel) and parse those values and put into a query.
    text area:
    ":P11_text"
    query:
    "select *
    from table
    where column in :P11_text;"
    I have tried some variations of replace and translate in order to parse that list of values...something like: translate(:P11_text, chr(10)||chr(13), ',' ).....and many variations of this.
    I have been able to replace the end of lines with the commas, but it appears that I am not getting my single quotes captured, even when trying to force them in. The best attempt returned single quotes and commas in between values but not at the beginning and end of the list of values.
    I would bet that there is an easy way to accomplish this or an easy way to accomplish the requirement in a different way altogether.
    Please point me in the right direction.

    I finally got this one figured out!
    create or replace type myTableType as table
    of varchar2(4000)
    create or replace
    function in_list( p_string in varchar2 ) return myTableType
    as
    l_string long default p_string || ',';
    l_data myTableType := myTableType();
    n number;
    begin
    loop
    exit when l_string is null;
    n := instr( l_string, ',' );
    l_data.extend;
    l_data(l_data.count) :=
    ltrim( rtrim( substr( l_string, 1, n-1 ) ) );
    l_string := substr( l_string, n+1 );
    end loop;
    return l_data;
    end;
    --The SQL Query is:
    select *
    from t wher c in (select *
    from THE
    ( select cast( in_list(translate(:p10_prolist,chr(10)||chr(13),',')) as
    mytableType ) from dual ) a);
    --Working like a champion!!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Starting and stopping an SQL query from within a Shell script

    DB version:10gR2
    OS Version:AIX
    We have a C++ application called WpnCreate.cpp, which is causing some locking problems.
    So, we have decided to capture(using SPOOL) the locking info(session info, blocking program,..etc) using an SQL query.
    WpnCreate.cpp program is initiated by a shell script. So we need this SQL query(.sql) to start firing just before WpnCreate.cpp is called and when WpnCreate.cpp has finished executing, we need the SQL query execution to stop.
    But how do i stop the sql query execution? Should i capture the session id and serial# of this session and use kill -9 at the end of the shell script?
    Flow of the Shell script should be like this
    Step1. Start firing the SQL query which captures the locking info and SPOOL them to a file
    Step2. Execute WpnCreate.cpp program
    Step3. Stop the firing of SQL query once WpnCreate.cpp has finished executing ( i don't know how)How will i go about achieving this?

    How can you run your step 2 untill & unless your step 1 gets over. You can run in background but then it will not capture the correct information.
    I think you need to run your step 1 after step 2 , then only you will be able to capture the information.
    You can run your C++ program in background and can wait for some time using sleep command and then run the query to check the locking information.

  • HOW TO FIND AND CORRECT THE SQL QUERY ERRORS ????

    Sometimes I get the errors while executing the sql queries.
    I just wanted to know about the various ways by which I can find the sql query errors .
    Any suggestions will be deeply appreciated.

    If you get the an error from SSMS and you can't comprehend it, you can google the error message and google would always lead you to the correction. Or you can post the error in this forum, people
    here are always kind and ready to help :).
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Need help in rewriting a sql query

    Can any one please tell me if there is any utility that can help me correcting the sql I have I need to tune the query as its taking lot of time. I want to use some tool that will help me re-formating the query.
    Any help in this regard will be highly appreciated.

    If you think that Oracle SQL Tuning Tools like SQL Tuning Advisor and SQL Access Advisor are not helping.
    You might look into thrid party tools like Quest- SQL Navigator and TOAD.
    But I don't advise this based on the following:
    Re: Oracle Third Party Tools and Oracle Database
    Oracle have enough tools of its own to satisfy the various needs.
    Adith

  • Rewrite a sql query

    Hi All
    i want to rewite the sql from
    select x
    from table1 t1
    where y =
    ( select max(y) from table1 t2 where t1.id = t2.id )
    to be more simple
    i believe that analytic functions can do that
    i tried
    select x
    from table1
    having y = max(y) over()
    but it did not work
    any help please
    thanks

    thanks for all of you
    i have rewriten the query , BUT the code did not become smaller , and i don't know which execution plan is better , any suggestions?
    Old SQL:
    SELECT scl1.claim_type,
    scp.publisher_no,
    scp.publisher_percentage,
    sys.dual_claim_publisher_no,
    effective_date
    FROM song_claims scl1, song_claim_publishers scp, system_parameters sys
    WHERE scl1.song_claim_no = scp.song_claim_no
    AND scl1.song_no = 2
    AND scl1.effective_date =
    SELECT MAX(scl2.effective_date)
    FROM song_claims scl2
    WHERE scl2.song_no = 21
    AND (scl2.effective_date <= '01-jan-2000'
    OR scl2.effective_date =
    SELECT MIN(scl3.effective_date)
    FROM song_claims scl3
    WHERE scl3.song_no = 2
    Old SQL Execution Plan:
    SELECT STATEMENT, GOAL = CHOOSE               Cost=8     Cardinality=1     Bytes=30
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIM_PUBLISHERS     Cost=3     Cardinality=1     Bytes=10
    NESTED LOOPS               Cost=8     Cardinality=1     Bytes=30
    NESTED LOOPS               Cost=5     Cardinality=1     Bytes=20
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIMS     Cost=3     Cardinality=1     Bytes=17
    INDEX UNIQUE SCAN     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=2     Cardinality=1     
    SORT AGGREGATE                    Cardinality=1     Bytes=12
    FIRST ROW               Cost=3     Cardinality=1     Bytes=12
    INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
    SORT AGGREGATE                    Cardinality=1     Bytes=12
    FIRST ROW               Cost=3     Cardinality=1     Bytes=12
    INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
    TABLE ACCESS FULL     Object owner=WISSYS     Object name=SYSTEM_PARAMETERS     Cost=2     Cardinality=1     Bytes=3
    INDEX RANGE SCAN     Object owner=CRS     Object name=XPKSONG_CLAIM_PUBLISHERS     Cost=2     Cardinality=1     
    New SQL:
    select * from
    SELECT scl1.claim_type,
    scp.publisher_no,
    scp.publisher_percentage,
    sys.dual_claim_publisher_no,
    scl1.effective_date,
    max (effective_date) over (partition by null) max_eff_date,
    min (effective_date) over (partition by null) min_eff_date
    FROM song_claims scl1, song_claim_publishers scp, system_parameters sys
    WHERE scl1.song_claim_no = scp.song_claim_no
    AND scl1.song_no = 2
    where
    effective_date = case when max_eff_date <= '01-jan-2000' then to_char(max_eff_date)
    when min_eff_date > '01-jan-2000' then to_char(min_eff_date)
    else (SELECT to_char(MAX(effective_date)) FROM song_claims scl2 WHERE scl2.song_no = 2 and scl2.effective_date < '01-jan-2000')
    end
    New SQL Execution Plan:
    SELECT STATEMENT, GOAL = CHOOSE               Cost=10     Cardinality=1     Bytes=69
    VIEW     Object owner=BFH          Cost=10     Cardinality=1     Bytes=69
    WINDOW BUFFER               Cost=10     Cardinality=1     Bytes=30
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIM_PUBLISHERS     Cost=3     Cardinality=1     Bytes=10
    NESTED LOOPS               Cost=8     Cardinality=1     Bytes=30
    MERGE JOIN CARTESIAN               Cost=5     Cardinality=1     Bytes=20
    TABLE ACCESS FULL     Object owner=WISSYS     Object name=SYSTEM_PARAMETERS     Cost=2     Cardinality=1     Bytes=3
    BUFFER SORT               Cost=3     Cardinality=1     Bytes=17
    TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIMS     Cost=3     Cardinality=1     Bytes=17
    INDEX RANGE SCAN     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=2     Cardinality=1     
    INDEX RANGE SCAN     Object owner=CRS     Object name=XPKSONG_CLAIM_PUBLISHERS     Cost=2     Cardinality=1     
    SORT AGGREGATE                    Cardinality=1     Bytes=12
    FIRST ROW               Cost=3     Cardinality=1     Bytes=12
    INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
    Thanks

  • Command the execute sql query and does not clean up data in Table

    Hi Team
    I have an SP, which writes source and target data to Temp Tables and runs except query to get mismatch details
    I am using Exec command to execute source query that writes data to Temp Table, once I execute query using Exec, data is written and immediately #temp table is cleaned, now I cannot use #temp table for comparition.
    Is there any way to execute sql query in SP without using EXEC and will hold the data in temp table.

    You need to create temp table before EXEC statement and rewrite your dynamic query also as below
    declare @source_Sql nvarchar(1000)
    ,@target_Sql nvarchar(1000)
    create table #TempTable1 (name nvarchar(10))
    create table #TempTable2 (name nvarchar(10))
    set @source_Sql = 'INSERT INTO #TempTable1 SELECT [Name] from Employee'
    set @target_Sql = 'INSERT INTO #TempTable2 SELECT [Name] from Employee2'
    EXEC (@source_Sql)   
    EXEC (@target_Sql)             
    select * from #TempTable1 
     Except 
    select * from #TempTable2

  • Rewrite sql query

    Hello,
    I need to rewrite this SQL query to give the same result, but in more resorcefull manner.
    Probably using aggregation, but I am not sure.
    Can somebody give me a head start.
    desc resource_bundles
    Name          Null     Type               
    LOCALE        NOT NULL CHAR(5)            
    BUNDLE_NAME   NOT NULL VARCHAR2(32)       
    RESOURCE_NAME NOT NULL VARCHAR2(64)       
    VALUE_STRING           VARCHAR2(2048 CHAR)
    select a.bundle_name,a.resource_name, a.value_string as Czech,(select b.value_string
                                             from resource_bundles b
                                             where b.bundle_name = a.bundle_name
                                             and b.resource_name = a.resource_name
                                             and b.locale = 'en_US'
                                            )as English,
                                             (select c.value_string
                                             from resource_bundles c
                                             where c.bundle_name = a.bundle_name
                                             and c.resource_name = a.resource_name
                                             and c.locale = 'ru_RU'
                                             ) as Russian,
                                             (select d.value_string
                                             from resource_bundles d
                                             where d.bundle_name = a.bundle_name
                                             and d.resource_name = a.resource_name
                                             and d.locale = 'it_IT'
                                            ) as Italian
    from resource_bundles a
    where a.locale = 'cs_CZ';Thank you
    Edited by: BluShadow on 15-Apr-2011 12:20
    added {noformat}{noformat} tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    Also see the third post in this thread:
    {thread:id=2174552}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Can we change/Modify BI server generated Sql query and run to fetch data

    Hi,
    My client is saying that there is an option to modify bi server generated sql query to fetch data from source.
    question:As a request is made in presentation services, A dynamic sql query is generated and fetches data from source. all this is loggedin Nqlquery log..well can we change/modify the sql query generated and run modified sql query to fetch data from source. ., if so how? if not why?
    Thanks in advance
    Edited by: user10794468 on Jun 16, 2009 6:29 PM
    Edited by: user10794468 on Aug 12, 2009 6:58 PM

    Thank you so much for your reply..
    ..Can we also modify sql query generated by bi server to fetech data. the query's which we see in query log file..

  • Modes and Methods in Tag Query and SQL Query

    Hi,
    Can someone explain me about the modes available in <b>TAG Query and SQL Query.</b>
    TAG Query has modes such as <b>Current, CurrentWrite, GroupList, History, HistoryEvent, ModeList, Statistics and TagList</b>
    SQL Query i still have doubt on <b>FixedQuery with output , Modelist and TableList</b>
    I also need to know why methods are used?
    Thanks in advance
    Regards
    Muzammil

    I'll try to  explain to the best of my knowledge :
    <u><b>TagQuery</b></u>
    <b>Current</b> : Gives you the current value of the Tag you are reading.
    <b>CurrentWrite</b> : Let you write a Value as the Current Value of the Tag.
    <b>GroupList</b> : Generally Tags are grouped under different groups. Returns you the name of the Groups.
    <b>From the xMII Help Document :</b>
    <b>History</b> : History Mode returns interpolated data.  Interpolation can be accomplished by specifying either the # of rows desired or the retrieval resolution.  If the mode is "History" and a value is provided for the Resolution parameter (which is in seconds), the connector will retrieve evenly-spaced values starting at the beginning of the time interval, up to the maximum # of rows specified in the RowCount parameter.  If no value is provided for the Resolution parameter, the connector will return an evenly-spaced number of values based on the value of the RowCount parameter.
    For example, if the time interval is 1 hour, Resolution is 15, and RowCount is 240, the connector will return evenly spaced values each 15 seconds, up to 240 values (which would span the entire hour).
    If the time interval is 1 hour, Resolution is not provided or is set to zero, and RowCount is 120, the connector would return 120 evenly spaced values, at an effective interval of 30 seconds.
    <b>HistoryEvent Mode</b> : The connector can provide historical values "as they were stored" the database.  This mode provides no interpolation of values.
    <b>Statistics Mode</b> : When retrieving data for statistical calculations, the connector utilizes the same techniques as in the "HistoryEvent"  mode.  It is important to note that the first two returning columns in the HistoryEvent query must be the timestamp and the value, in that order.  The SAP xMII Statistical processor expects that order, or errors will occur.  This ensures precision of statistical measurements, particularly time-weighted average, by using the exact storage time and values from the historical database.  The SAP xMII system provides the statistical calculations.
    <b>Modelist</b> : Basically returns the modes of the Query Available. The Data returned is same as the data in the Modes list in the Quert Template Editor.
    <b>Taglist</b> : Returns all the Tags in the Datasource.
    <u><b>SQL Query</b></u>
    <b>Modelist</b> : Same as above.
    <b>TableList</b> : List of all the tables in the database to which the connector connects.
    Again from SAP xMII Help Documentation :
    <b>FixedQueryWithOutput</b> : This mode is used to execute an Oracle stored procedure or function that returns a REF CURSOR as output.  The position of the REF CURSOR is marked by a "?" in the query.  For example:
    <b>Create a table.</b>
    <i>create table usage (id int, name varchar(50));
    insert into usage (id, name) values (1, 'test1');
    insert into usage (id, name) values (2, 'test2');
    insert into usage (id, name) values (3, 'test3');
    insert into usage (id, name) values (4, 'test4');
    insert into usage (id, name) values (5, 'test5');
    insert into usage (id, name) values (6, 'test6');
    insert into usage (id, name) values (7, 'test7');
    insert into usage (id, name) values (8, 'test8');</i>
    <b>Define the stored procedure.</b>
    <i>DROP PACKAGE foopkg;
    CREATE PACKAGE foopkg IS
      TYPE cursortype is ref cursor;
      PROCEDURE test (mycursor in out cursortype);
    END foopkg;
    CREATE PACKAGE BODY foopkg IS
      PROCEDURE test (mycursor in out cursortype) AS
      BEGIN
         open mycursor for select * from usage;
      END;
    END foopkg;
    </i>
    Define a query template for calling the stored procedure.  Enter the following in the FixedQuery tab:
    <b>call foopkg.test(?)</b>
    This template returns all rows from the Usage table.

  • How to modify a SQL query?

    Hi all,
    I am using Crystal Reports version 10. I have a number of reports that have been written by a software vendor wherby the name of the database they were connected to when the report was written is coded into the FROM command of the reports SQL query, eg "GCUK_2" in the of the SQL snippet below.
    SELECT "Clients"."NAME", "Quotes"."QUOTE_ID", "Quote_Items"."UPRICE", "Quote_Items"."QTY", "Quote_Items"."UOM", "Quote_Items"."QUSAGE_ID", "Report_Control"."QUSAGEID", "Quote_Items"."STANDARD", "Quote_Items"."SECT_FLAG", "Quote_Items"."DISPORDER", "Quotes"."DESCRIPT", "Report_Control"."SECT_NAME", "Quote_Items"."CNT", "Category_and_Type"."TYPEDESC", "Quote_Items"."DESCRIPT", "Report_Control"."DISP_SORT"
    FROM   ((("GCUK_2"."schedwin"."QTE_CTRL" "Report_Control" INNER JOIN "GCUK_2"."schedwin"."QUSAGE" "Quote_Items" ON "Report_Control"."QUSAGEID"="Quote_Items"."QUSAGE_ID") LEFT OUTER JOIN "GCUK_2"."schedwin"."QUOTES" "Quotes" ON
    I have tried setting the Datasource Location, but it doesn't change the query at all. I have read on another forum that you can generate another SQL query using the Database Expert, Current Connections, then right click the Add Command for the database you want to create a SQL command. Is this the only way to update the database names in the query?
    Thanks,
    Scott.

    Hi Sourashree,
    Thanks for that. All the reports were created by the vendor using tables as opposed to the command object. I would have thought that changing the datasource would automatically cause Crystal to rewrite the SQL query syntax, but this doesn't appear to be the case.
    Yes, I've noticed that modifying the record selection will change the sql query. The only way I can see to change the database name in the query is to change to the desired databsource and then remove and re-insert the tables, which will then update the query with the correct name. However, this seems to be a convoluted way of changing the db name in the query.

  • SQL query execution Issue

    Hi,
    Facing Database performance issue while runing overnight batches.
    Generate tfprof output for that batch and found some sql query which is having high elapsed time. Could any one please let me know what is the issue for this. It will also be great help if anyone suggest what need to be done as per tuning of this sql queries so as to get better responce time.
    Waiting for your reply.
    Effected SQL List:
    INSERT INTO INVTRNEE (TRANS_SESSION, TRANS_SEQUENCE, TRANS_ORG_CHILD,
    TRANS_PRD_CHILD, TRANS_TRN_CODE, TRANS_TYPE_CODE, TRANS_DATE, INV_MRPT_CODE,
    INV_DRPT_CODE, TRANS_CURR_CODE, PROC_SOURCE, TRANS_REF, TRANS_REF2,
    TRANS_QTY, TRANS_RETL, TRANS_COST, TRANS_VAT, TRANS_POS_EXT_TOTAL,
    INNER_PK_TECH_KEY, TRANS_INNERS, TRANS_EACHES, TRANS_UOM, TRANS_WEIGHT,
    TRANS_WEIGHT_UOM )
    VALUES
    (:B22 , :B1 , :B2 , :B3 , :B4 , :B5 , :B21 , :B6 , :B7 , :B8 , :B20 , :B19 ,
    NULL, :B9 , :B10 , :B11 , 0.0, :B12 , :B13 , :B14 , :B15 , :B16 , :B17 ,
    :B18 )
    call count cpu elapsed disk query current rows
    Parse 722 0.09 0.04 0 0 0 0
    Execute 1060 7.96 83.01 11442 21598 88401 149973
    Fetch 0 0.00 0.00 0 0 0 0
    total 1782 8.05 83.06 11442 21598 88401 149973
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    UPDATE /*+ ROWID(TRFDTLEE) */TRFDTLEE SET TRF_STATUS = :B2
    WHERE
    ROWID = :B1
    call count cpu elapsed disk query current rows
    Parse 635 0.03 0.01 0 0 0 0
    Execute 49902 14.48 271.25 41803 80704 355837 49902
    Fetch 0 0.00 0.00 0 0 0 0
    total 50537 14.51 271.27 41803 80704 355837 49902
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    DECLARE
    var_trans_session     invtrnee.trans_session%TYPE;
    BEGIN
    -- ADDED BY SHANKAR ON 08/29/97
    -- GET THE NEXT AVAILABLE TRANS_SESSION
    bastkey('trans_session',0,var_trans_session,'T');
    -- MAS001
    uk_trfbapuo_auto(var_trans_session,'UPLOAD','T',300);
    -- MAS001 end
    END;
    call count cpu elapsed disk query current rows
    Parse 0 0.00 0.00 0 0 0 0
    Execute 1 24191.23 24028.57 8172196 10533885 187888 1
    Fetch 0 0.00 0.00 0 0 0 0
    total 1 24191.23 24028.57 8172196 10533885 187888 1
    Misses in library cache during parse: 0
    Misses in library cache during execute: 1
    Optimizer goal: CHOOSE
    SELECT INNER_PK_TECH_KEY
    FROM
    PRDPCDEE WHERE PRD_LVL_CHILD = :B1 AND LOOSE_PACK_FLAG = 'T'
    call count cpu elapsed disk query current rows
    Parse 1 0.01 0.00 0 0 0 0
    Execute 56081 1.90 2.03 0 0 0 0
    Fetch 56081 11.07 458.58 53792 246017 0 56081
    total 112163 12.98 460.61 53792 246017 0 56081
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    ******************

    First off, be aware of the assumptions I'm making. The SQL you presented above strongly suggests (to me at least) that you have cursor for loops. If that's the case, you need to review what their purpose is and look to convert them into single statement DML commands. For example if you have something like this
    DECLARE
        ln_Count        NUMBER;
        ln_SomeValue    NUMBER;
    BEGIN
        FOR lcr_Row IN (    SELECT pk_id,col1,col2 FROM some_table)
        LOOP
            SELECT
                COUNT(*)
            INTO
                ln_COunt
            FROM
                target_table
            WHERE
                pk_id = lcr_Row.pk_id;
            IF ln_Count = 0 THEN
                SELECT
                    some_value
                INTO
                    ln_SomeValue
                FROM
                    some_other_table
                WHERE
                    pk_id = lcr_Row.col1
                INSERT
                INTO
                    target_table
                    (   pk_id,
                        some_other_value,
                        col2
                VALUES
                    (   lcr_Row.col1,
                        ln_SomeValue,
                        lcr_Row.col2
            ELSE
                UPDATE
                    target_table
                SET
                    some_other_value = ln_SomeValue
                WHERE
                    pk_id = lcr_Row.col1;
            END IF;
        END LOOP;
    END;                            it could be rewritten as
    DECLARE
    BEGIN
        MERGE INTO target_table b
        USING ( SELECT
                    a.pk_id,
                    a.col2,
                    b.some_value
                FROM
                    some_table a,
                    some_other_table b
                WHERE
                    b.pk_id = a.col1
               ) e
        ON (b.pk_id = e.pk_id)
        WHEN MATCHED THEN
          UPDATE SET b.some_other_value = e.some_value
        WHEN NOT MATCHED THEN
          INSERT (  b.pk_id,
                    b.col2,
                    b.some_other_value)
          VALUES(   b.pk_id,
                    b.col2,
                    b.some_value);
    END;It's going to take a bit of analysis and work but the fastest and most scalable way to approach processing data is to use SQL rather than PL/SQL. PL/SQL data processing i.e. cursor loops should be an option of last resort.
    HTH
    David

  • Get a insert session value for SQL query at report

    Hi friends
    I created a global temp table and procedure to support web search form.
    and a search result report. The procudure
    gets search result from multip tables and
    insert into temp table --recordsearch. I can get value from temp table  by call procedure
    at SQL*Plus.
    However, I can not get this value by web report.
    How can I get this insert session value and pass to SQL query for report?
    Thanks,
    Newweb
    CREATE GLOBAL TEMPORARY TABLE recordsearch
    (emp_id          VARCHAR2(200),
    ssn               VARCHAR2(9),
    fname          VARCHAR2(200),
    lname           VARCHAR2(200),
    m_name          VARCHAR2(200)
    ) ON COMMIT PRESERVE ROWS;

    it possible that your web form does not have a persistent, dedicated connection. if you have connection pooling for example, multiple sessions will see the same instance of the GTT, so if one deletes it, then nobody sees it (or you can see others data). if the connections are not persistent, then they can disconnect between calls, deleting the GTT table.

  • SQL query with Java Server Pages

    Hey,
    I'm trying to read some information from database with SQL Query. How I can put the parameter that I get from previous *.jsp page to SQL query?
    Technologies that I use are WML, JSP and MySQL.
    I can get the parameter by method getParameter() and it is correct.
    But how to but the requested parameter into sql query and complete the sql query?
    Should I read it to some variable before putting it to sql query?
    */ this works fine */
    out.println("<p>periodi"+request.getParameter("periodi"+"loppu</p>");
    /* this doesn't work */
    ResultSet tulokset = lause.executeQuery("select * from kurssi where periodi='+request.getParameter("periodi")+'");
    /* this doesn't work */
    String periodi=request.getParameter("periodi");
    ResultSet tulokset = lause.executeQuery("select * from kurssi where periodi='periodi' '");
    Thanks,
    Rampe

    Hey,
    I'm trying to read some information from database
    se with SQL Query. How I can put the parameter that I
    get from previous *.jsp page to SQL query?
    Technologies that I use are WML, JSP and MySQL.
    I can get the parameter by method getParameter()
    () and it is correct.
    But how to but the requested parameter into sql
    ql query and complete the sql query?
    Should I read it to some variable before putting it
    it to sql query?
    */ this works fine */
    out.println("<p>periodi"+request.getParameter("periodi"
    "loppu</p>");
    /* this doesn't work */
    ResultSet tulokset = lause.executeQuery("select * from
    kurssi where
    periodi='+request.getParameter("periodi")+'");
    /* this doesn't work */
    String periodi=request.getParameter("periodi");
    ResultSet tulokset = lause.executeQuery("select *
    * from kurssi where periodi='periodi' '");
    Thanks,
    RampeTry this
    ResultSet tulokset = lause.executeQuery("select * from kurssi where periodi=" + "'" +request.getParameter("periodi")+"' " );this should work

  • Sql query not executed using recordset

    Hi All,
    I am trying to first format and then execute SQL query statement using recordset object with DI API. the issue is with vb.net's string formatting. I want to use 'USE [DB_Name]' statement in SQL and then 'Alter Procedure ..' statement. as this has to be the first statement in sql , I am using 'GO' in between and seperating each sentence with following syntax.
      Dim AltProc  as string
      AltProc = " USE [DB_name]" & Environment.NewLine
      AltProc = AltProc & " GO " &  Environment.NewLine
      AltProc = AltProc & " ALTER proc [proc_name] " &  Environment.NewLine
    '---------------------and so on
    Orec.DoQuery(AltProc)
    this formatting does not recognize new line and gives 'incorrect syntax near 'Go'' error.  strange thing is, if I take this query in SQL, it runs perfectly and I can see it getting formatted with each new line created. I tried even VbcrLf but it didnt work.
    any one has any idea?
    thanks in advance,
    Binita

    HI Binita
    The reason:
    GO is the "command" delimiter of MS Query Editor.
    It is not working with RecordSet Object.
    In MS SQL 2008 version you can define the schema before the procedure name but in SQL server 2000/2005 it is not possible.
    IN SQL 2008 use the Fully Qualified name instead of GO:
    Dim AltProc  as string
      AltProc = " ALTER proc [DB_name].[dbo].[proc_name] "  + vbcrlf
    '---------------------and so on
    Orec.DoQuery(AltProc)
    it is not working on MS SQL 2008 i have tried.
    'CREATE/ALTER PROCEDURE' does not allow specifying the database name as a prefix to the object name.'
    Regards,
    J.
    Edited by: Janos  Nagy on Jun 22, 2009 2:55 PM

Maybe you are looking for

  • Continuous play of different slideshows

    I've created 3 slideshows for a graduation party. I want to play them on my IMac continuously. Is there a way to do that in IPhoto, combining all slideshows (I did read a previous post that suggested I create a playlist of my 3 songs and build the sl

  • Expanding root partition in Solaris 10 VirtualBox virtual machine

    I am running a Solaris 10 u8 x86 64-bit guest as a VirtualBox VM on a WinXP x64 host. I was running out of space in the guest VM, so I used CloneVDI (http://forums.virtualbox.org/viewtopic.php?f=6&t=22422) to clone and expand the VM from 20GB to 30GB

  • PDF files are not opening even i have latest reader and re-installed firefox

    I am able to open in IE and Chrome but in FF it always shows that not able to open - the reader plug-in starts, open a blank window with caption "PDF might not be displayed properly" when downloaded, it opens fine with Adobe Reader.

  • ITunes freezes when iPhone plugged in

    So I've uninstalled and reinstalled iTunes twice, reset the iPhone settings and whenever I plug the phone in, iTunes freezes. The phone charges and appears in iPhoto, but no dice with iTunes. My iPod shows up fine. I haven't installed anything new on

  • How many DADs are too many?

    I've read on mod_plsql performance tuning pages that fewer is better but how much of a hit does another DAD really cause? I'm wondering if we could stop running multiple applications under a DAD and break them up by application. Say we went from 6 to