Dynamic SQL help!

I'm trying to build a update statement with different operator which setup from a table and passed. Not sure how to build it. Please help
PROCEDURE my_update
  p_id            IN NUMBER,
  p_var1          IN NUMBER,
  my_value        IN VARCHAR2,
  my_operator     IN VARCHAR2,
  x_return_status OUT VARCHAR2,
  x_errors        OUT VARCHAR2
) IS
  l_dynamic_string VARCHAR2(4000);
BEGIN
l_dynamic_string := table_b.col2 ||
                    rec.my_operator  /* value as: "=" OR "LIKE" */ ||
                    my_value /* VALUE AS "2233"  OR "900%" */
  UPDATE table_b
     SET col1 = ''
   WHERE id = p_id
     AND l_dynamic_string
     AND id = (SELECT table_a.id
                 FROM table_a
                WHERE id = p_id
                  AND col_a = p_var1);
EXCEPTION
  WHEN OTHERS THEN
    NULL;
END my_update;

Hi,
What you posted can probably be done without dynamic SQL. If the expression after LIKE does not conatin a wild-card, then LIKE behaves just like =. You can probably arrange things so that the query always uses LIKE.
If you need dynamic SQL, then use EXECUTE IMMEDIATE to perform it.
I think you want something like this:
PROCEDURE my_update
  p_id            IN NUMBER,
  p_var1          IN NUMBER,
  my_value        IN VARCHAR2,
  my_operator     IN VARCHAR2,
  x_return_status OUT VARCHAR2,
  x_errors        OUT VARCHAR2
) IS
  l_dynamic_string VARCHAR2 (4000);
  l_update_txt        VARCHAR2 (4000);
BEGIN
    l_dynamic_string := table_b.col2 || ' '     -- If my_operator is LIKE you'll need a space here
                                    || my_operator               /* value as: "=" OR "LIKE" */
                         || Q'< '>'
                         || my_value            /* VALUE AS "2233"  OR "900%" */
                         || Q'<' >'
    l_update_txt := 'UPDATE table_b'
                || '   SET col1 = NULL'
              || ' WHERE id = p_id'
                || '   AND ' || l_dynamic_string
                || '   AND id = (SELECT table_a.id'
                 || '                     FROM table_a'
                 || '             WHERE id = p_id
                 || '               AND col_a = p_var1)';
    dbms_output.put_line (l_update_txt || ' = l_update_txt in my_update');
--  EXECUTE IMMEDIATE  l_update_txt;
--     No EXCEPTION hider
END my_update;While writing dynamic SQL, it's a good idea to display the dynamic text. I used put_line to do that. Remember to comment out (or remove) the display code when testing is finished.
Notice that the EXECUTE IMMEDIATE command is commented out. Only after you've tested some, and you think l_update_txt is correct, should you un-commnet that line.
Never say "EXCEPTION WHEN OTHERS THEN NULL;"
Error messages help you, especially duting development when you're likely to have lots of coding errors.
If you really need to keep the program running after encountering certain errors, then it's okay to have an EXCEPTION block, but your use of either "WHEN OTHERS" or "THEN NULL" should be very limited, and you should not use both of them together.

Similar Messages

  • Pl Dynamic sql help needed

    Hello Everyone
    I am using database 11g. Can someone pl suggest what are the rules for putting single quotes for dynamic sql like
    1) how many single quotes before/after a sql statement .
    2) Rules for putting single quotes if there exists i) a variable in the sql statement
    ii) a constant for e.g 100 in the sql statment.
    If you could give the answers with a simple select statement, it will be even better !!!
    Thanks and regards
    Gautam

    ms wrote:
    Hello Everyone
    I am using database 11g. Can someone pl suggest what are the rules for putting single quotes for dynamic sql like
    1) how many single quotes before/after a sql statement .
    2) Rules for putting single quotes if there exists i) a variable in the sql statement
    ii) a constant for e.g 100 in the sql statment.
    If you could give the answers with a simple select statement, it will be even better !!!
    Thanks and regards
    Gautamwrite the SQL statement as you would for any SQL client & enclose it using Q-quote
    http://askanantha.blogspot.com/2007/12/q-quote-operator-introduced-in-oracle.html
    Handle:     ms
    Status Level:     Newbie
    Registered:     Jun 3, 2007
    Total Posts:     46
    Total Questions:     17 (17 unresolved)
    WOW!
    *NEVER got any answer in 5+ years & still wasting time here again, still!
    You must be an eternal optimist.
    I hope I get credited for your FIRST answer.

  • Dynamic SQL Help - Getting Errors

    Basically I have a table with employee data, and I'm trying to create a dynamic PL / SQL block that creates a new table and copies over the data from employee table to the new one.
    I'm teaching myself dynamic SQL so this is practice. Please don't offer "better solutions" because I'm sure there are plenty - I'm just looking to complete the code as is so I better understand this query language.
    Here is my code:
    set serveroutput on size 10000
    declare
    cursor c is
    select table_name, tablespace_name
    from user_tables where table_name = 'EMP';
    cursor c2 is
    select table_name, column_name, data_length, data_type, data_precision
    from user_tab_cols where table_name = 'EMP';
    cursor c3 is
    select *
    from emp;
    counter number(3);
    counter := 0;
    begin
    for i in c loop
    if (counter = 0) then
    create table emp2;
    insert into emp2 table_name, tablespace_name;
    for i in c2 loop
    insert into emp2 table_name, column_name, data_length, data_type, data_precision;
    counter := counter + 1;
    end loop;
    end loop;
    for i in c3 loop
    insert into emp2 empno, ename, job, mgr, hiredate, sal, comm, deptno;
    end loop;
    end;
    Here are my errors:
    Error starting at line 3 in command:
    declare
    cursor c is
    select table_name, tablespace_name
    from user_tables where table_name = 'EMP';
    cursor c2 is
    select table_name, column_name, data_length, data_type, data_precision
    from user_tab_cols where table_name = 'EMP';
    cursor c3 is
    select *
    from emp;
    counter number(3);
    counter := 0;
    begin
    for i in c loop
    if (counter = 0) then
    create table emp2;
    insert into emp2 table_name, tablespace_name;
    for i in c2 loop
    insert into emp2 table_name, column_name, data_length, data_type, data_precision;
    counter := counter + 1;
    end loop;
    end loop;
    for i in c3 loop
    insert into emp2 empno, ename, job, mgr, hiredate, sal, comm, deptno;
    end loop;
    end;
    Error report:
    ORA-06550: line 14, column 13:
    PLS-00103: Encountered the symbol "=" when expecting one of the following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table long double ref
    char time timestamp interval date binary national character
    nchar
    The symbol "<an identifier>" was substituted for "=" to continue.
    ORA-06550: line 19, column 7:
    PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:
    ( begin case declare exit for goto if loop mod null pragma
    raise return select update while with <an identifier>
    <a double-quoted delimited-identifi
    06550. 00000 - "line %s, column %s:\n%s"
    *Cause:    Usually a PL/SQL compilation error.
    *Action:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Start reading the Documents
    There are basic errors in your code, some are pointed out below
    declare
      cursor c is
        select table_name, tablespace_name
        from user_tables where table_name = 'EMP';
      cursor c2 is
        select table_name, column_name, data_length, data_type, data_precision
        from user_tab_cols where table_name = 'EMP';
      cursor c3 is
        select *
        from emp;
      counter number(3);
      counter := 0; --"You cannot initiate variable like this"
    begin
      for i in c loop
       if (counter = 0) then
         create table emp2; --"You cannot create tables directly in PL/SQL. Need to use dynamic SQL.Syntax also wrong. "
         insert into emp2 table_name, tablespace_name; --"Values caluse missing"
         for i in c2 loop
            insert into emp2 table_name, column_name, --"Values caluse missing"
               data_length, data_type, data_precision; --"Record syntax not used"
            counter := counter + 1;
      end loop;
      end loop;
      for i in c3 loop
        insert into emp2 empno, ename,
         job, mgr, hiredate, sal, comm, deptno; --"Values caluse missing"
      end loop;
    end;

  • Adding filter conditions dynamically in WHERE clause -dynamic SQL help

    Here I have a simple condition but very complicated query. Basically, I have to put a filter condition in my where clause. "Location" comes to the stored procedure as parameter. Plus there are other parameters as well.
    If location = "all", I can run the query simply and get the result. But when Location = "CA", which is just a subset of "ALL" then I am having hard time putting one -- AND statement in WHERE clause.
    This query is designed for location = 'ALL'
    open cv for
    'Select col1, col2, col3, Col4
    from t1, t2, t3
    WHERE condition1
    AND condition2
    AND condition3'
    AND location = location_id --- This should only run if location IS NOT ALL
    I have written a dynamic query but it doesn't work for that part. Any ideas will be appreciated. Thanks,

    From what I understood
    If location = 'ALL' then
    fetch all the records
    Else
    add extra filter location_id = <supplied location id>
    End If
    If this is the condition the following logic should solve your issue.
    open cv for
    'Select col1, col2, col3, Col4
    from t1, t2, t3
    WHERE condition1
    AND condition2
    AND condition3'
    AND ((location_id = location_id and location = 'ALL') or (location_id = location))Regards
    Raj

  • Need help on Dynamic SQL Cursor in Forms

    Hi All,
    I am trying to execute Dynamic SQL Cursor in forms using EXEC_SQL built in.
    I have a cursor for example:
    'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order
    My code is
    cur_num := Exec_SQL.Open_cursor;
    sql_order := 'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order;
    EXEC_SQL.PARSE(cursor_number, sql_order);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,1,ln_Supp_Id);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,2,ls_Suppl_Name,30);
    EXEC_SQL.DEFINE_COLUMN(cur_num ,24,ls_exchange,20);
      sql_count := EXEC_SQL.EXECUTE(cur_num );
      While EXEC_SQL.FETCH_ROWS(cur_num ) > 0 Loop
            EXEC_SQL.COLUMN_VALUE(cur_num ,1,ln_Supp_Id);
            EXEC_SQL.COLUMN_VALUE(cur_num ,2,ls_Suppl_Name);
            EXEC_SQL.COLUMN_VALUE(cur_num ,24,ls_exchange);
    End Loop;
    EXEC_SQL.CLOSE_CURSOR(cur_num );
    In this case I have to write 24 Define Columns and 24 Column value. Is there any way to assign them to %rowtype at one time as I need all coulmn of the table.
    I had similar case on multiple tables.
    Please help me
    Thanks,
    Maddy

    I need this dynamic sql because p_supplier and p_order values changes at run time
    I do not understand. Is this a simplified sample or the real thing? You do know that you can pass variables to cursors:
    cursor test is
    select * from supplier where supplier = p_supplier and processing_order = p_order;
    or does e.g. p_supplier hold other parts of the query?
    cheers

  • Help Needed in Dynamic Sql or alternate to Dynamic Sql

    Hi Am working in sqlserver 2008 R2 and here is my Table structure and SPC
    ;create table SalaryReport(IdSalary int primary key identity(1,1),
    IDMainCompany int,IDSubCompany int,Salary money,Incentive int,NoofEmployees int, SalaryDate datetime, Creditscore int );
    insert into SalaryReport (IDMainCompany,IDSubCompany,Salary,Incentive,NoofEmployees,SalaryDate,Creditscore)
    ( Select 100 as IDMainCompany , 1000 as IDSubCompany ,200000 AS Salary, 20000 as Incentive, 500 as NoofEmployees,
    '2014-01-01' as SalaryDate, 60 as Creditscore union all
    Select 100 as IDMainCompany , 1001 as IDSubCompany ,300000 AS Salary, 40000 as Incentive, 600 as NoofEmployees,
    '2014-01-01' as SalaryDate , 70 as Creditscore union all
    Select 100 as IDMainCompany , 1002 as IDSubCompany ,400000 AS Salary, 40000 as Incentive, 1500 as NoofEmployees,
    '2014-01-01' as SalaryDate , 45 as Creditscore union all
    Select 101 as IDMainCompany , 1003 as IDSubCompany ,30000 AS Salary, 2000 as Incentive, 100 as NoofEmployees,
    '2014-01-01' as SalaryDate, 60 as Creditscore union all
    Select 102 as IDMainCompany , 1004 as IDSubCompany ,450000 AS Salary, 25000 as Incentive, 700 as NoofEmployees,
    '2014-01-01' as SalaryDate, 30 as Creditscore)
    Sample Test Script:
    DECLARE @IDMainCompany int = 100;
    DECLARE @Process_Date datetime = '2014-01-01';
    declare @Query nvarchar(max);
    SELECT
    CAST(SR.IDMainCompany AS VARCHAR(12)) AS IDMainCompany
    ,CAST(SR.IDSubCompany AS VARCHAR(12)) AS IDSubCompany
    ,CAST(SR.Salary AS VARCHAR(12)) AS Salary
    ,CAST(SR.Incentive AS VARCHAR(12)) AS Incentive
    ,CAST(SR.NoofEmployees AS VARCHAR(12)) AS NoofEmployees
    ,CAST(SR.SalaryDate AS VARCHAR(15)) AS SalaryDate
    ,CAST((SR.Creditscore) AS VARCHAR(15)) AS average
    FROM SalaryReport SR
    WHERE SR.IDMainCompany = @IDMainCompany
    AND DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
    UNION ALL
    SELECT
    '' AS IDMainCompany
    ,'' AS IDSubCompany
    ,'Total: ' + CAST(SUM(SR.Salary) AS VARCHAR(12)) AS Salary
    ,'Total: ' + CAST(SUM(SR.Incentive) AS VARCHAR(12)) AS Incentive
    ,'Total: ' + CAST(SUM(SR.NoofEmployees) AS VARCHAR(12)) AS NoofEmployees
    ,'' AS SalaryDate
    ,'Total: ' +CAST(avg(SR.Creditscore) AS VARCHAR(12)) AS Totalaverage
    FROM SalaryReport SR
    WHERE SR.IDMainCompany = @IDMainCompany
    AND DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
    group by IDMainCompany, DATEPART(MM, SalaryDate)
    the sample data i posted is having less columns. actually i have 20 columns in the select list. Also the parameters to the where condition i gave two i.e IDMainCompany, SalaryDate. I will also need to use IDSubCompany for some case. My skeleton will be 
    Create Procedure Test(@IDMainCompany int, @IDSubCompany int = null, @SalaryDate datetime)
    as
    BEGIN
    IF(@IDMainCompany is not null && @IDMainCompany > 0 && @SalaryDate is not null && @SalaryDate <> ' ' &&
    @IDSubCompany is null)
    BEGIN
    --The logic what discussed on previous posts will falls here with @IDMainCompany, @SalaryDate as parameter to the where condition
    END
    IF(@IDMainCompany is not null && @IDMainCompany > 0 && @SalaryDate is not null && @SalaryDate <> ' ' &&
    @IDSubCompany is null && @IDSubCompany > 0 )
    BEGIN
    --The logic what discussed on previous posts will falls here with @IDMainCompany, @SalaryDate,@IDSubCompany as parameter to the where condition
    END
    END
    As said i need to include 20 columns in the select list and as union all used on the previous sample there are 20 columns on the first query and 20 columns on the second query after the union all. The SPC will become big. If i repeat this for second if condition,
    it will be too big. How can i reduce this writing more lines.
    I am aware of the concept dynamic sql. Is there any other way to do this? or if dynamic sql is the only option, can anyone help me rewriting this select statements as dynamic sql
    Could anyone please assist me 
    loving dotnet

    >>
    thanks for your reply and yes, i am invoking this from my asp.net application using C# language.  Would you like to share something?
    <<
    Yes,
    You can use client side dynamic sql. I'm not talking about concatenating strings. I'm talking about using Runtime Text Tamplates (preprocesed templates in Visual Studio 2010).
    Add a new "Runtime Text Template" item to your VS project. Be "MyReportTemplate.tt" the file name of the runtime text template.  The content of this file should be something like the following:
    <#@ template language="C#" #>
    <#@ assembly name="System.Core" #>
    SELECT
    -- part of your query goes here
    -- the interesting part come next
    FROM
    SalaryReport SR
    WHERE
    SR.IDMainCompany = @IDMainCompany
    <# if (IDSubCompany.HasValue && IDSubCompany.Value > 0) { #>
    AND SR.IDSubCompany = @IDSubCompany
    <# } #>
    AND
    DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
    GROUP BY
    IDMainCompany, DATEPART(MM, SalaryDate)
    Add a new c# code file named MyReportTemplate.partial.cs closed to MyReportTemplate.tt with the following code:
    public partial class MyReportTemplate
    public int? IDSubCompany { get; set; }
    Then, to execute the query you can write a code similar to the following:
    public DataTable ExecuteReport(int mainCompanyId, int? subCompanyId, DateTime processDate )
    using (var cn = CreateConnection())
    using (var cmd = new SqlCommand())
    using (var adapter = new SqlDataAdapter(cmd))
    cmd.Connection = cn;
    var template = new MyReportTemplate
    IDSubCompany = subCompanyId
    cmd.CommandText = template.TransformText();
    cmd.Parameters.AddWithValue("@IDSubCompany", subCompanyId == null ? (object) DBNull.Value : subCompanyId.Value);
    cmd.Parameters.AddWithValue("@IDMainCompany", mainCompanyId);
    cmd.Parameters.AddWithValue("@Process_Date", processDate);
    var table = new DataTable();
    adapter.Fill(table);
    return table;
    EntityLite: A Lightweight, Database First, Micro ORM

  • Dynamic sql in a trigger ...please help

    HI All,
    I've got a really large table called 'shop' of the form
    id number, product1_cost number, product2_cost number,product3_cost, product4_cost....and so on until product20_cost,
    product1_desc, product2_desc....and so so on until..product20_desc, active, start_date, end_date, usercreated,
    useramended.
    I have now created a new application. The new table is called 'products' which has an id, cost, description, oldproductid, shopid
    I need a trigger on the table shop so that if anyone uses the old application, it automatically creates the product rows in my new table 'products'
    Not all the product fields on the 'shop' table have data so I only want to migrate data if necessary.
    The trigger would do the following:
    1. Loop through all the products, if the product was updated and product number does not exist on 'products.oldproductid' then create a new record in products
    2. If product was updated and product number does exist then simply update the product details.
    I have got the trigger to work with product1. However, I'm finding it difficult to write some sort of dynamic sql that would
    do the same check on all 20 products without having to repeat the code 20 times.
    can someone help?
    CREATE OR REPLACE TRIGGER TR_PRODCOST
    AFTER UPDATE ON SHOP
    FOR EACH ROW
    DECLARE
    v_oldproductid products.oldpackageid%TYPE;
    v_datedl products.datedl%TYPE;
    v_product_sq number;
    v_status number := 1;
    v_cost number(11, 2);
    v_old_pkg number:= :old.product1_cost;
    v_new_pkg number:= :new.product1_cost;
    v_old_desc varchar2(100):= :old.product1_desc;
    v_new_desc varchar2(100):= :new.product1_desc;
    v_old_shop varchar2(10):= :old.shopid;
    v_new_shop varchar2(10):= :new.shopid;
    CURSOR get_newproduct_cur IS
    SELECT p.oldproductid, p.datedl
    FROM products p
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    BEGIN
    IF nvl(v_new_pkg, -1) <> nvl(v_old_pkg, -1) THEN
    OPEN get_newproduct_cur;
    FETCH get_newproduct_cur
    INTO v_oldproductid, v_datedl;
    IF get_newproduct_cur%NOTFOUND THEN
    v_oldproductid := null;
    v_datedl := null;
    END IF;
    CLOSE get_newproduct_cur;
    IF v_oldproductid is null THEN
    SELECT SEQ_products.nextval INTO v_product_sq FROM dual;
    INSERT into products p
    (product_ID,
    SHOPID,
    DESCRIPTION,
    COST,
    DATECR,
    USERCR,
    OLDproductID,
    SHORT_DESCRIPTION)
    VALUES
    (v_product_sq,
    v_new_shop,
    v_new_desc,
    v_new_pkg,
    sysdate,
    'OLFORMS',
    1,
    v_new_desc);
    ELSE
    IF v_new_pkg is null THEN
    UPDATE products p
    set p.datedl = sysdate,
    p.cost = 0.00
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    ELSE
    UPDATE products p
    set p.cost = v_new_pkg,
    p.datedl = null,
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    END IF;
    IF v_new_desc = v_old_desc THEN
    v_status := 1;
    ELSE
    UPDATE products p
    SET p.description = v_new_desc
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    END IF;
    END IF;
    ELSE
    END IF;
    END IF;
    END;

    Hi All,
    Thanks about your advice on the relational design. However, this is only a temporary fix. The old shop table was created about 10 years ago by someone else. Our users have to use the old pages for about 2-3 weeks and therefore I need a quick fix that will create the products on the new tables.
    The other problem I have is that another powerbuilder based applicated also uses the same tables and that application is being modified to use the new tables but not until another 3 weeks. To ensure both systems are available in parallel, I have to implement this temporary solution.
    B_Binoy, you seem you have a solution there but I didn't quite get it. I tried putting the whole pl/sql block in a string, replacing the '1' in product 1 using a variable x and then using execute immediate but because of the :new and :old bind variables, it kept giving me errors like 'variables not bound' etc. If you don't mind, please can you expand on your solution?
    Many Thanks

  • Help required in changing to str for dynamic sql

    Hi
    I am trying to make this to string for dynamic sql, this is a part of the sql which is giving problem with p_..as parameters from proc. Help me in this , iam also seeing dbms _output but stil unable to format it to required error free string.
    || ' AND ( po.abbreviationprojectopportid LIKE '
    || '%'
    || 'NVL'
    || '('
    || p_opp_code
    || ', ''NULL'')'
    || '%'
    || ' OR co.companyname LIKE '
    || '%'
    || 'NVL'
    || '('
    || p_client_name
    || ', '' NULL'')'
    || '%'
    || ' OR le.line_item_amount = NVL '
    || ' ('
    || p_booking_amt
    || ', -0.197) '
    || 'OR po.dealcurrency = NVL '
    || '('
    || p_currency
    || ',''NULL'')'
    || 'OR be.booking_entry_id LIKE '
    || '%'
    || 'NVL ('
    || p_entry_id
    || ',''NULL'')'
    || '%'
    || ' OR le.line_item_id LIKE '
    || '%'
    || 'NVL ('
    || p_line_item
    || ',''null'')'
    || '%'
    || ' OR be.ticket_num LIKE '
    || '%'
    || 'NVL ('
    || p_ticket_num
    || ',''NULL'')'
    || '%'
    || ' OR be.updatedby LIKE '
    || '%'
    || 'NVL ('
    || p_user_name
    || ',''NULL'')'
    || '%'
    || ' OR credittransaction.acct_code ='
    || 'NVL ('
    || p_gl_account
    || ','
    || '-0.197)'
    || 'OR debittransaction.acct_code ='
    || 'NVL ('
    || p_gl_account
    || ', '
    || '-0.197) '
    || 'OR credittransaction.profit_ctr_code ='
    || 'NVL ('
    || p_profit_center
    || ','
    || ' -0.197)'
    || 'OR debittransaction.profit_ctr_code ='
    || 'NVL ('
    || p_profit_center
    || ','
    || '-0.197)'
    || ' OR le.sap_posting = NVL ('
    || p_sap_posting
    || ',''$'')'
    || 'OR cmis.cmis_code = NVL ('
    || p_cmis_nominal
    || ','' -0.197)'
    || 'OR sa.sap_code = NVL ('
    || p_sap_booking_entity
    || ', -0.197)'
    || ' OR (be.booking_date BETWEEN '
    || v_booking_date_from
    || 'AND '
    || v_booking_date_to
    || ')'
    || ' )'
    || 'ORDER BY '
    || p_sort_by
    || ' '
    || p_order;

    some errors.. Try this...
    ' SELECT be.booking_date bookingdate, '
    || ' be.booking_entry_id entryid, le.line_item_id itemid,'
    || ' po.abbreviationprojectopportid opportunitycode,'
    || ' co.companyname clientname, '
    || ' le.line_item_amount bookingamount,'
    || ' be.ticket_num ticketnum, po.dealcurrency currency,'
    || ' cmis.cmis_code cmis_nominal,'
    || ' sa.sap_code sap_booking_entity,'
    || ' (SELECT full_name '
    || ' FROM iba_employee '
    || ' WHERE TO_CHAR (employeeid) = be.updatedby) updatedby,'
    || ' be.updateddate updateddate, '
    || ' (SELECT le.line_item_amount * rate '
    || ' FROM iba_currencyconversion '
    || ' WHERE tocurrencycd = '
    || 'USD'
    || ' AND currencycd = po.dealcurrency '
    || ' AND conversiondate = be.booking_date) amountusd,'
    || 'debittransaction.acct_code debitglaccount,'
    || ' credittransaction.acct_code creditglaccount,'
    || ' debittransaction.profit_ctr_code debitprofitcenter,'
    || ' credittransaction.profit_ctr_code creditprofitcenter,'
    || ' debittransaction.amt debitamount,'
    || ' credittransaction.amt creditamount'
    || ' FROM rb_booking_entry be, '
    || ' rb_line_item le, '
    || ' rb_booking_period bp,'
    || ' rb_cmis_gl_account cmisgl,'
    || ' rb_cmis_account cmis,'
    || ' iba_projectopportunity po,'
    || ' iba_company co,'
    || ' rb_sap_account sa,'
    || ' (SELECT acctr.line_item_id line_item,'
    || ' sapgl_acc.account_code acct_code,'
    || ' acctr.amount amt,'
    || ' sappr.profit_center_code profit_ctr_code'
    || ' FROM rb_account_transaction acctr,'
    || ' rb_sap_profit_center sappr,'
    || ' rb_sap_gl_account sapgl_acc'
    || ' WHERE acctr.profit_center_id = sappr.profit_center_id '
    || ' AND acctr.gl_account_id = sapgl_acc.gl_account_id '
    || ' AND acctr.transaction_type = ''D'') debittransaction,'
    || ' (SELECT acctr.line_item_id line_item,'
    || ' sapgl_acc.account_code acct_code,'
    || ' acctr.amount amt,'
    || ' sappr.profit_center_code profit_ctr_code '
    || ' FROM rb_account_transaction acctr, '
    || ' rb_sap_profit_center sappr, '
    || ' rb_sap_gl_account sapgl_acc '
    || ' WHERE acctr.profit_center_id =sappr.profit_center_id '
    || ' AND acctr.gl_account_id = sapgl_acc.gl_account_id '
    || ' AND acctr.transaction_type = ''C'') credittransaction '
    || ' WHERE po.projectopportunityid = be.projectopportunityid '
    || ' AND be.booking_entry_id = le.booking_entry_id '
    || ' AND po.companyid = co.companyid '
    || ' AND bp.booking_period_id = be.booking_period_id '
    || ' AND cmis.cmis_id = cmisgl.cmis_id '
    || ' AND le.sap_id = sa.sap_id '
    || ' AND le.cmis_id = cmis.cmis_id '
    || ' AND debittransaction.line_item(+) = le.line_item_id '
    || ' AND credittransaction.line_item(+) = le.line_item_id '
    || ' AND ( po.abbreviationprojectopportid LIKE ' || '''%' || NVL(p_opp_code,'NULL') || '%'''
    || ' OR le.line_item_id LIKE '
    || '''%'
    || NVL (
    || p_line_item
    || ,'null')
    || '%'''
    | ' OR le.line_item_amount = '
    ||NVL(|| p_booking_amt, -0.197)
    || ' OR po.dealcurrency ='
    || NVL(p_currency,'NULL')
    || ' OR be.booking_entry_id LIKE '
    || '''%'
    || NVL (p_entry_id,'NULL')
    || '%'''
    || ' OR be.ticket_num LIKE '
    || '''%'
    || NVL (p_ticket_num,'NULL')
    || '%'''
    || ' OR be.updatedby LIKE '
    || '''%'
    || NVL (p_user_name,'NULL')
    || '%'''
    || ' OR credittransaction.acct_code ='
    || NVL (p_gl_account,-0.197)
    || ' OR debittransaction.acct_code ='
    || NVL (p_gl_account,  -0.197)
    || ' OR credittransaction.profit_ctr_code ='
    || NVL (p_profit_center, -0.197)
    || ' OR debittransaction.profit_ctr_code ='
    || NVL (p_profit_center, -0.197)
    || '  OR le.sap_posting = '
    ||NVL (p_sap_posting,'$')
    || ' OR cmis.cmis_code = '
    ||NVL (p_cmis_nominal, -0.197)
    || ' OR sa.sap_code = '
    || NVL (p_sap_booking_entity, -0.197)
    || '  OR (be.booking_date BETWEEN to_date('''
    || v_booking_date_from
    || ''') AND  to_date('''
    || v_booking_date_to
    || ''')'
    || ' OR co.companyname LIKE '
    || '''%'
    || NVL(p_client_name,'NULL')
    || '%'''
    || ' )'
    || 'ORDER BY  ' || p_sort_by || ',' || p_order;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help to make this dynamic sql work

    Hi,
    I have many DDLs to execute and these DDLs change over time, so I try to load these DDLs into a table (y) and write a proc to loop through them. But I run into some problems and need your help.
    Here are the details:
    create table y ( x varchar2(4000));
    CREATE TABLE error_log (
    error_log_ID NUMBER(20),
    statement VARCHAR2(2000),
    error_msg VARCHAR2(400),
    Action VARCHAR2(16)
    CREATE SEQUENCE SEQ_error_log
    START WITH 1
    INCREMENT BY 1
    NOMINVALUE
    NOMAXVALUE
    NOCYCLE
    CACHE 20
    NOORDER
    CREATE OR REPLACE PROCEDURE CUST_UPDATE1 (
    schema_name IN VARCHAR2 ,
    table_tablespcae_name IN VARCHAR2,
    index_tablespcae_name IN VARCHAR2
    ) AS
    v_code NUMBER;
    v_errm VARCHAR2(400);
    sql_stmt1 VARCHAR2(3000) ;
    CURSOR c1 IS SELECT x FROM y;
    BEGIN
    FOR i IN c1 LOOP
    sql_stmt1 := i.x;
    DBMS_OUTPUT.PUT_LINE ( 'x = '|| sql_stmt1 );
    / **************************** worked if use this hard coded ********************************
    sql_stmt1 := 'CREATE TABLE '||schema_name||'.zz
    aa VARCHAR2(4) NOT NULL,
    bb VARCHAR2(100) NOT NULL,
    cc VARCHAR2(2) NOT NULL
    TABLESPACE '|| table_tablespcae_name;
    BEGIN
    EXECUTE IMMEDIATE sql_stmt1;
    EXCEPTION
    WHEN OTHERS THEN
    v_code := SQLCODE;
    v_errm := SUBSTR(SQLERRM, 1 , 400);
    INSERT INTO error_log VALUES ( SEQ_error_log.nextval, sql_stmt1, v_errm, DECODE(v_code, -1430, 'IGNORE', 'CHECK') );
    END;
    END LOOP;
    END;
    Test:
    exec cust_update1('SCOTT', 'USERS', 'c'); -- didn't use last parameter
    Senario 1. insert into y values (
    'CREATE TABLE schema_name.zz
    aa VARCHAR2(4) NOT NULL,
    bb VARCHAR2(100) NOT NULL,
    cc VARCHAR2(2) NOT NULL
    TABLESPACE table_tablespcae_name ' );
    ===> error_log show: ORA-01918: user 'SCHEMA_NAME' does not exist
    Senario 2. insert into y values (
    '''CREATE TABLE ''||schema_name||''.zz
    aa VARCHAR2(4) NOT NULL,
    bb VARCHAR2(100) NOT NULL,
    cc VARCHAR2(2) NOT NULL
    TABLESPACE ''|| table_tablespcae_name' );
    ==> error_log show: ORA-00900: invalid SQL statement
    3. I hard coded the exact dynamic from step 2 and assigned to sql_stmt1, ( as commeted out in my code) it WORKED.
    Thanks
    George

    hi,
    do the scenario1 but you have to substitute the schema_name and table_space name with your actual string before calling the dynamic sql.
    ei.
    sql_stmt1 := replace(sql_stmt1,'schema_name',schema_name);
    sql_stmt1 := replace(sql_stmt1,'table_tablespcae_name',table_tablespcae_name);
    BEGIN
    EXECUTE IMMEDIATE sql_stmt1;
    EXCEPTION
    WHEN OTHERS THEN
    v_code := SQLCODE;
    v_errm := SUBSTR(SQLERRM, 1 , 400);
    INSERT INTO error_log VALUES ( SEQ_error_log.nextval, sql_stmt1, v_errm, DECODE(v_code, -1430, 'IGNORE', 'CHECK') );
    END;
    Cheers,
    J

  • Help on Execute Immediate Dynamic Sql

    Hi all
    when i run the following Pl/SQL,nothing is happening
    I want to pass array to following procedure
    DECLARE
    SQL_STMT      VARCHAR2(1000);
    BEGIN
    SQL_STMT  := 'Select '|| '''populate_table_test(''' || '|| chr(39)||id_name||chr(39)||' ||''','''||'|| chr(39)||attribute1||chr(39)||' ||''','''||'|| chr(39)||attribute2||chr(39)||' ||''');'''||' from table_test1';
    dbms_output.put_line(sql_stmt);
    execute immediate sql_stmt;
    Exception when others then
    dbms_output.put_line(sqlerrm);
    end;
    SQL> ed
    Wrote file afiedt.buf
      1  Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
      2  chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
      3* table_test
    SQL> /
    'POPULATE_TABLE_TEST('||CHR(39)||ID_NAME||CHR(39)||','||CHR(
    populate_table_test('AAA','AA','AA');
    populate_table_test('AAA','AA','AA');
    CREATE
      TABLE TABLE_TEST1
        "ID_NO"      NUMBER(10,0)     ,
        "ID_NAME"    VARCHAR2(10 BYTE),
        "ATTRIBUTE1" VARCHAR2(10 BYTE),
        "ATTRIBUTE2" VARCHAR2(10 BYTE)
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    commit;
    CREATE TABLE TABLE_TEST
    (ID_NO NUMBER(10) ,
    id_NAME VARCHAR2(10) ,
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    select * from "TABLE_TEST";
    CREATE OR REPLACE TYPE T_TYPE IS OBJECT (
    id_NAME VARCHAR2(10),
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    Create or replace  type TB_T_TYPE as varray(200) of  T_TYPE ;
    CREATE OR REPLACE
    PROCEDURE POPULATE_TABLE_TEST (EXAMPLE IN TB_T_TYPE) AS
    begin
    FOR I IN 1..EXAMPLE.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ID_NAME);
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE1);
    DBMS_OUtPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE2);
    insert into TABLE_TEST(id_name,attribute1,attribute2)
    values (treat(example(i) as T_TYPE).id_NAME,
    treat(example(i) as T_TYPE).ATTRIBUTE1,
    treat(example(i) as T_TYPE).ATTRIBUTE2
    end loop;
    end; Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
    chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
    table_test
    Edited by: user1849 on Nov 30, 2011 12:40 PM
    Edited by: user1849 on Nov 30, 2011 1:18 PM

    user1849 wrote:
    Hi all
    when i run the following Pl/SQL,nothing is happeningRemember to issue the SQL*Plus command
    SET  SERVEROUTPUT  ONbefore running it; otherwise, you won't see the output from dbms_output.
    >
    I want to pass array to following procedureIs this a procedure or an anonymous PL/SQL block?
    If it's a procedure, post the entire procedure, starting with CREATE [OR REPLACE] PROCEDURE...
    Never write, let alone post, unformatted code. Indent the code to show the scope of BEGIN, LOOP, etc.
    DECLARE
    SQL_STMT      VARCHAR2(1000);
    BEGIN
    SQL_STMT  := 'Select '|| '''populate_table_test(''' || '|| chr(39)||id_name||chr(39)||' ||''','''||'|| chr(39)||attribute1||chr(39)||' ||''','''||'|| chr(39)||attribute2||chr(39)||' ||''');'''||' from table_test1';
    dbms_output.put_line(sql_stmt);
    execute immediate sql_stmt;
    Exception when others then
    dbms_output.put_line(sqlerrm);
    end;
    /Only use an EXCEPTION handler when you can improve on the default error handling. The default is to print an error message, so there's no point in you explicitly doing the same.
    Why do you need dynamic SQL? Post the output results you want to get from the sample data you posted.
    Given that you do need dynamic SQL, why can't you use bind variables, rather than including the values as literals?
    Given that you have to use literals, use Q-notation for strings that include single-quote characters.
    http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements003.htm#sthref337
    For example:
    ...     SQL_STMT  := Q{'Select  populate_table_test ('}'
              || id_name
              || Q'{','}'
              || attribute1
              || Q'{','}'
    SQL> ed
    Wrote file afiedt.buf
    1  Select 'populate_table_test('|| chr(39)||id_name||chr(39)||','||
    2  chr(39)||attribute1||chr(39)||','|| chr(39)||attribute2||chr(39)||');' from
    3* table_test
    SQL> /
    'POPULATE_TABLE_TEST('||CHR(39)||ID_NAME||CHR(39)||','||CHR(
    populate_table_test('AAA','AA','AA');
    populate_table_test('AAA','AA','AA');
    CREATE
    TABLE TABLE_TEST1
    "ID_NO"      NUMBER(10,0)     ,
    "ID_NAME"    VARCHAR2(10 BYTE),
    "ATTRIBUTE1" VARCHAR2(10 BYTE),
    "ATTRIBUTE2" VARCHAR2(10 BYTE)
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    Insert into TABLE_TEST1 (ID_NO,ID_NAME,ATTRIBUTE1,ATTRIBUTE2) values (null,'AAA','AA','AA');
    commit;
    Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful.
    Is that the best sample data for testing? Wouldn't it be better to have at least one row that was not the same as all the others?
    CREATE TABLE TABLE_TEST
    (ID_NO NUMBER(10) ,
    id_NAME VARCHAR2(10) ,
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    select * from "TABLE_TEST";
    CREATE OR REPLACE TYPE T_TYPE IS OBJECT (
    id_NAME VARCHAR2(10),
    ATTRIBUTE1 VARCHAR2(10),
    ATTRIBUTE2 VARCHAR2(10)
    Create or replace  type TB_T_TYPE as varray(200) of  T_TYPE ;
    CREATE OR REPLACE
    PROCEDURE POPULATE_TABLE_TEST (EXAMPLE IN TB_T_TYPE) AS
    begin
    FOR I IN 1..EXAMPLE.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ID_NAME);
    DBMS_OUTPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE1);
    DBMS_OUtPUT.PUT_LINE(TREAT(EXAMPLE(I) AS T_TYPE).ATTRIBUTE2);
    insert into TABLE_TEST(id_name,attribute1,attribute2)
    values (l_t_seq(i),
    treat(example(i) as T_TYPE).id_NAME,
    treat(example(i) as T_TYPE).ATTRIBUTE1,
    treat(example(i) as T_TYPE).ATTRIBUTE2
    end loop;
    end; You're trying to INSERT 4 values into 3 columns. Did you mean to say "insert into TABLE_TEST( *id_no,* id_name,attribute1,attribute2)"?
    What is l_t_seq? Post complete test scripts that people can run to re-create the problem and test their ideas.

  • Help With SUBSTR in dynamic SQL statement

    Following is the dynamic SQL statement.
    EXECUTE IMMEDIATE 'UPDATE table_name pml
    SET pml.'|| con_fields.field ||' = SUBSTR(pml.'||con_fields.field||' ||'' ''||
    (SELECT pml1.'||con_fields.field||'
    FROM table_name pml1
    WHERE pml1.grp_id = '||los_concats.grp_id ||'
    AND pml1.row_id = '||los_concats.row_id||'
    AND pml1.loser_flg = ''Y''),1, '||con_fields.max_length||')
    WHERE pml.grp_id = '||los_concats.grp_id ||'
    AND pml.loser_flg IS NULL ';
    what it does is that it updates a particular field. This field is concatenated by a field of a similar record.
    My problem is with SUBSTR function. Since I am concatenating fields I do not want the field to be updated greater than max_length on that field, the reason why I use SUBSTR. the select query inside SUBSTR works alright with one of the AND condition in a WHERE clause not present. When I add that additional condition it gives me this error.
    ORA-00907: missing right parenthesis.
    Is there any way to get around this problem. Does SQL has other than SUBSTR function which can limit the character length.
    Appreciate it.

    The other alternative I thought about was to do this first
    EXECUTE IMMEDIATE 'SELECT pml.'||con_fields.field||'
    FROM table_name pml
    WHERE pml.grp_id = '||los_concats.grp_id||'
    AND pml.row_id = '||los_concats.row_id||'
    AND pml.loser_flg = ''Y''
    ' INTO v_concat_field;
    write into the variable v_concat_field and then use it into the previous script.
    But on this I get SQL Command not properly terminated, I don't get it Why?
    Donald I tried with your suggested script. It works fine with one of the conditions eliminated. I don't understand what the error trying to say?
    Thanks

  • Help with dynamic SQL

    Hello,
    I have the following function that works ok:
    CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    cursor c is select A.partition_name from (select table_name, partition_name,
    extractvalue (
    dbms_xmlgen.
    getxmltype (
    'select high_value from all_tab_partitions where table_name='''
    || table_name
    || ''' and table_owner = '''
    || table_owner
    || ''' and partition_name = '''
    || partition_name
    || ''''),
    '//text()') import_value from all_tab_partitions) A where table_name = sTable and A.import_value = iImportIndex;
    sPartitionName VARCHAR(20);
    err_num NUMBER;
    BEGIN
    open c;
    fetch c into sPartitionName;
    IF c%ISOPEN THEN
    CLOSE c;
    END IF;
    RETURN sPartitionName;
    EXCEPTION
    WHEN OTHERS THEN
    err_num := SQLCODE;
    --save error in log table
    LOG.SAVELINE(SQLCODE, SQLERRM);
    END Get_Partition_Name;
    I am trying to replace the cursor statement with dynamic SQL, something like (see below) but it doesn't work any more; I think I am missing some quotes.
    CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
    RETURN VARCHAR2 IS
    TYPE t1 IS REF CURSOR;
    c t1;
    sSql VARCHAR2(500);
    sPartitionName VARCHAR(20);
    err_num NUMBER;
    BEGIN
    sSql := 'select A.partition_name from (select table_name, partition_name,
    extractvalue (
    dbms_xmlgen.
    getxmltype (
    ''select high_value from all_tab_partitions where table_name=''''
    || table_name
    || '''' and table_owner = ''''
    || table_owner
    || '''' and partition_name = ''''
    || partition_name
    || ''''''),
    ''//text()'') import_value from all_tab_partitions) A where table_name = :a and A.import_value = :b';
    OPEN c FOR sSql USING sTable, iImportIndex;
    fetch c into sPartitionName;
    IF c%ISOPEN THEN
    CLOSE c;
    END IF;
    RETURN sPartitionName;
    EXCEPTION
    WHEN OTHERS THEN
    err_num := SQLCODE;
    --save error in log table
    LOG.SAVELINE(SQLCODE, SQLERRM);
    END Get_Partition_Name;
    Please advise,
    Regards,
    M.R.

    Assuming the requirement is to find the partition in the supplied table with the supplied high value and the issue is that dba/all_tab_partitions.high_value is a long, one alternative along the same lines as you've done already is as follows. (I've just used a cursor rather than a function for simplicity of demo).
    SQL> var r refcursor
    SQL> set autoprint on
    SQL> declare
      2   ctx dbms_xmlgen.ctxhandle;
      3   v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
      4   v_value      NUMBER       := 100;
      5  begin
      6   ctx := DBMS_XMLGEN.NEWCONTEXT
      7          ('select table_name
      8            ,      partition_name
      9            ,      high_value  hi_val
    10            from   dba_tab_partitions
    11            where  table_name     = :table_name');
    12   dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
    13   open:r for
    14   with x as
    15   (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
    16    from   dual)
    17   select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
    18   ,      extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
    19   ,      extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
    20   from   x
    21   ,      TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
    22   where  extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
    23  end;
    24  /
    PL/SQL procedure successfully completed.
    TABLE_NAME
    PARTITION_NAME
    HI_VAL
    LOGMNR_USER$
    P_LESSTHAN100
    100
    SQL> I'm sure there are other ways as well. Especially with XML functionality, there's normally many ways to skin a cat.

  • Dynamic sql giving error --please help

    Hi ,
    I have written the following code --
    CREATE OR REPLACE FUNCTION tabcount (
    tab IN VARCHAR2, field IN VARCHAR2 ,whr IN VARCHAR2)
    RETURN INTEGER
    IS
    retval INTEGER;
    BEGIN
    DBMS_OUTPUT.PUT_LINE ('whr' ||whr);
    DBMS_OUTPUT.PUT_LINE ('field1' ||field);
    EXECUTE IMMEDIATE
    ' SELECT COUNT(*) FROM ' || tab ||
    ' WHERE ' || field || 'like '/'%'||whr ||'%'/''
    INTO retval;
    DBMS_OUTPUT.PUT_LINE ('countis!' ||retVal);
    RETURN retval;
    END tabcount;
    It is giving the following error--
    ORA-00920: invalid relational operator
    ORA-06512: at "TABCOUNT", line 10
    ORA-06512: at line 2
    I am not sure how to enclose the like operator within the single quotes.Double quotes is not working for me.
    Thanx in advance,
    Ira

    Offhand, it looks like you may still have some syntax problems -- probably need a blank space before the WHERE --maybe some other stuff too.
    What you need to do to debug it is this (and this works just about anytime you are having trouble with dynamic SQL):
    1. store the sql statement in a variable.
    2. Use DBMS_OUTPUT to display your select statement BEFORE calling execute immediate.
    3. copy/paste that select into a separate window and run/debug it.
    4. Once you know what is wrong with that statement, go back and fix the code accordingly.
    Have fun,
    --scott                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to rename C00n generic column names in a Dynamic SQL report

    I have a an interface whereby the user can select 1 to 60 (upper limit) columns out of 90 possible columns (using a shuttle) from one table before running a report.
    To construct the SQL that will eventually execute, I'm using a "PLSQL function body returning SQL query" with dynamic SQL. The only problem is that I have to use "Generic Column Names" option to be able to compile the code and end up with c001 to c060 as the column names.
    How can I use the names of the selected columns as the report headings rather than c001, C002... etc?
    I do not know beforehand which columns, or how many columns or the order of the selected columns.
    I know Denes K has a demo called Pick Columns but I can't access his code. I have a hunch though that he may be just using conditions to hide/show the apropriate columns.
    thanks in advance
    PaulP

    Hi Paul
    I would change the Heading Type in the Report Details screen to PLSQL and use the shuttle item to return the column values. e.g.
    RETURN :p1_shuttle;
    I'm assuming the shuttle already has a colon separated list of the column headings in the correct order?
    I hope that helps
    Shunt

  • Unique id in dynamic sql

    hi all,
    I am using oracle 10g version.
    I have one table but i do not have any unique id to identify the row.
    I want to have a unique id temporarily in my select statement (dynamic sql) in a stored procedure while fetching the results, so that i can return my results along with the unique id through the cursor.
    Please help me...
    Thanks in advance to all...

    it depends if you have a more than one column that you can uniquely identify and put them together by concatenating you can have a unique id. or a rowid might help you to temporarily identify a row.
    SQL> select e.* from employee e;
    FNAME           MINIT LNAME           SSN       BDATE       ADDRESS                        SEX       SALARY SUPERSSN         DNO
    John            B     Smith           123456789 09-Jan-1965 731 fONDREN, hOUSTON, TX       M       30000.00 333445555          5
    Frankin         T     Wong            333445555 08-Dec-1955 683 Voss, Houston,Tx           M       40000.00 888665555          5
    Alicia          J     Zelaya          999887777 19-Jul-1968 3321Castle, Spring, TX         F       25000.00 987654321          4
    Jennifer        S     Wallace         987654321 20-Jun-2041 291 Berry, Bellaire, TX        F       43000.00 888665555          4
    Ramesh          K     Narayan         666884444 15-Sep-1962 975 Fire Oak, Humble, TX       F       38000.00 333445555          5
    Joyce           A     English         453453453 31-Jul-1972 5631 Rice,Houston,TX           F       25000.00 333445555          5
    Ahmad           V     Jabbar          987987987 29-Mar-1969 980 Dallas,Houston, TX         M       25000.00 987654321          4
    James           E     Borg            888665555 10-Nov-2037 450 Stone, Houston, TX         M       55000.00                    1
    8 rows selected
    SQL> select rowid, e.* from employee e;
    ROWID              FNAME           MINIT LNAME           SSN       BDATE       ADDRESS                        SEX       SALARY SUPERSSN         DNO
    AAD8pbAAJAAAJ4fAAA John            B     Smith           123456789 09-Jan-1965 731 fONDREN, hOUSTON, TX       M       30000.00 333445555          5
    AAD8pbAAJAAAJ4fAAB Frankin         T     Wong            333445555 08-Dec-1955 683 Voss, Houston,Tx           M       40000.00 888665555          5
    AAD8pbAAJAAAJ4fAAC Alicia          J     Zelaya          999887777 19-Jul-1968 3321Castle, Spring, TX         F       25000.00 987654321          4
    AAD8pbAAJAAAJ4fAAD Jennifer        S     Wallace         987654321 20-Jun-2041 291 Berry, Bellaire, TX        F       43000.00 888665555          4
    AAD8pbAAJAAAJ4fAAE Ramesh          K     Narayan         666884444 15-Sep-1962 975 Fire Oak, Humble, TX       F       38000.00 333445555          5
    AAD8pbAAJAAAJ4fAAF Joyce           A     English         453453453 31-Jul-1972 5631 Rice,Houston,TX           F       25000.00 333445555          5
    AAD8pbAAJAAAJ4fAAG Ahmad           V     Jabbar          987987987 29-Mar-1969 980 Dallas,Houston, TX         M       25000.00 987654321          4
    AAD8pbAAJAAAJ4fAAH James           E     Borg            888665555 10-Nov-2037 450 Stone, Houston, TX         M       55000.00                    1
    8 rows selected
    SQL>

Maybe you are looking for