Dynamic sql newbie question

I am trying to do an insert statement dynamically inside a trigger. I want to concatenate the string 'IRFFFF' with substr(:new.stvterm_code,1,4).
Example: :new.stvterm_code is 200509... I only want 'IRFFFF2005'.
Here is my code....please help. The problem lies with the substr function and the :new operator.
code := ' ''IRFFFF'' || substr(:NEW.stvterm_code,1,4) ';
varsql := 'INSERT INTO ' || val_table || list || 'VALUES
(' || code || ',''y'',sysdate)';
cursor_handle := dbms_sql.open_cursor;
dbms_sql.parse(cursor_handle, varsql, dbms_sql.native);
feedback := dbms_sql.EXECUTE(cursor_handle);
COMMIT; for pl/sql developer only
dbms_sql.close_cursor(cursor_handle);
I get the following error:
ORA-01008: not all variables bound
ORA-06512: at "SYS.DBMS_SYS_SQL", line 1120
ORA-06512: at "SYS.DBMS_SQL", line 323
ORA-06512: at "SATURN.STW_STVTERM_A_I_ROW", line 169
ORA-04088: error during execution of trigger 'SATURN.STW_STVTERM_A_I_ROW'

code := 'IRFFFF' || substr(:new.stvterm_code,1,4);
varsql := 'INSERT INTO ' || val_table || list || 'VALUES(''' || code || ''',''y'',sysdate)';I would recommend though to use EXECUTE IMMEDIATE if possible, and bind variables in either case.

Similar Messages

  • Dynamic text - newbie question

    hello,
    i'm reviewing a lesson on Lynda.com. The subject is loading
    dynamic text from an external text file. Every time I try to access
    the dynamic text i've placed on the stage, I get an error: "Cannot
    access a property or method of a null object reference."
    I have two layers. Display and Actions. (Actions at the top.)
    The display layer has a keyframe in frame 1. on it, is a large
    instance of dynamic text. The instance name I've given it is
    "external_txt".
    Actions has a keyframe. In this frame i've got Lynda's action
    script, which is:
    var textLoader:URLLoader = new URLLoader();
    var textReq: URLRequest = new
    URLRequest('text/htmlText.txt');
    function textLoaded(event:Event):void
    external_txt.text = textLoader.data;
    textLoader.load(textReq);
    textLoader.addEventListener(Event.COMPLETE, textLoaded);
    in frame 2 of the Actions layer, I have a single command:
    stop();
    When I run this I can never assign a value to my dynamic
    text. Even if I try:
    function textLoaded(event:Event):void
    external_txt.text = 'smith';
    // external_txt.text = textLoader.data;
    --I get the error about the null object reference. For some
    reason I can not get my AS to set a property to the dynamic text on
    my stage.
    my publish settings are AS 3.0.
    does anyone have an idea what i'm doing wrong? Thanks.

    hi Ned,
    you've helped me again. Thanks.
    Putting stop in the first frame makes it now work. I don't
    really understand why, though.
    I had a 'stop' in frame 2 of my actions layer. so, when i ran
    what I started out with, with 'stop' in frame 2, when the playhead
    reaches frame one why can't I assign a value to the dynamic text
    instance?
    thanks.

  • Dynamic sql query question

    hi all,
    i created a report that displays results based on this query initially.
    select *
    from EMP
    where 1=1;
    i'm using a SQL Query (PL/SQL Function Body Returning SQL Query).
    i have search items in my page like empno, lastname, firstname, middle, email_address etc... when i place a value for lastname then in my query it should add AND LASTNAME = :P1_LASTNAME.
    so the query returned should now have
    select *
    from EMP
    where 1=1
    and LASTNAME = :P1_LASTNAME;
    is this possible?
    i was thinking something like looping for all search items in the page (ie. text, popup lov, datetimepicker) then check whether the item is null or not... when not null then probably get the substring of the item name like (ie. substr(:P1_LASTNAME) and get only LASTNAME then add "=" then concat it with the item name. not sure if this is possible though.
    thanks
    allen

    hi denes,
    thanks for the sample... i noticed that the sample hard codes additional conditions to be added to the sql query which is okay when the search criteria is less than 5-10... but i'm thinking if the search criteria will be like 15-30 fields or make all fields searchable, this might be uncomfortable.
    what i was thinking is like loop thru all the items i.e.
    declare
    sql varchar2(4000) := 'select * from emp where 1=1';
    begin
    for i in (select * from all_items_in_apex) -- this is just an example.
    loop
    if i.value is not null then
    sql := sql || ' and ' || i.column || '=' || i.value;
    end if;
    end loop;
    end;
    the only thing is that i don't know if there's a possible replacement for the clause (select * from all_items_in_apex).
    sorry if i'm asking too much but this is how i normally do it in forms. the suggestion in the link you provided should be sufficient but i was just wondering if this idea is also possible.
    thanks again.
    allen

  • PL/SQL Newbie Question

    Hey folks,
    I'll get this right out in the open. I'm a DBA. I have MINIMAL experience with PL/SQL so any helps, hints will go a LOOOONG way in helping me! I've got a user that wants to get a monthly report on disk usage for one of his databases. I've got a script that i can run and send the results, but i'd like to have this done automatically (who doesn't want things like this done automatically, right?)....
    I've got an email function that I use that works. I've tested that. I just need to stick the following select statement into the email. Even if I just get help where i can return the query correctly, I'll be happier than a pig in mud! I've got a feeling that I'll have to use a varray, but I'm very very shaky when it comes to getting to work.
    SELECT OWNER,round(SUM(BYTES)/1024/1024,2) MB
    FROM DBA_SEGMENTS
    WHERE OWNER IN ('QPROSPECT','QGIS','BASEMAP')
    GROUP BY OWNER
    ORDER BY OWNER;
    Again, any help is greatly appreciated!
    Thanks in advance,
    Jeremy

    Jeremy,
    If you are using 10g then you can use dbms_scheduler to automatically run this job other wise you can always rely on ever green cronjobs and shell script.
    You might have to create a procedure to calculate schema size and call it in usign dbms_scheduler
    BEGIN
       SYS.DBMS_SCHEDULER.create_job
          (job_name             => '"SYS"."MONTHLY_JOB"',
           job_type             => 'PLSQL_BLOCK',
           job_action           => 'begin
       SYS.calculate_schema_size;
    end;',
           repeat_interval      => 'FREQ=MONTHLY;BYMONTHDAY=-1;BYHOUR=4;BYMINUTE=0;BYSECOND=0',
           start_date           => SYSTIMESTAMP AT TIME ZONE 'US/Eastern',
           job_class            => 'DEFAULT_JOB_CLASS',
           comments             => 'calculate schema size monthly ',
           auto_drop            => FALSE,
           enabled              => FALSE
       SYS.DBMS_SCHEDULER.set_attribute
                                   (NAME           => '"SYS"."MONTHLY_JOB"',
                                    ATTRIBUTE      => 'job_priority',
                                    VALUE          => 1
       SYS.DBMS_SCHEDULER.set_attribute
                                   (NAME           => '"sys"."MONTHLY_JOB"',
                                    ATTRIBUTE      => 'max_failures',
                                    VALUE          => 3
       SYS.DBMS_SCHEDULER.ENABLE ('"SYS"."MONTHLY_JOB"');
    END;Regards

  • SQL Newbie Question

    Hi,
    I have the following data in a varchar2(20) column (phone_numbers)
    1.416.235.3456
    418.576.9806
    etc.
    I would like to manipulate the column so that the data is displayed as:
    14162353456
    4185769806
    Can somebody explain how this can be accomplished.
    Thanks

    Here's something that would work for all cases. Taking the first 14 characters might include the 'E' or '(blank)E', so translate turns those unwanted characters- including the period- into X's. Then replace turns all the X's into nulls.
    Note that I added in the '416.254.6790 Ext 3217' possibility.
    It might be wise to run an SQL to either erase the leading '1.' from all the phone numbers, or, to run an SQL that would add the leading '1.' to those numbers that didn't have it. That way, all your phone numbers look the same (except for the extension part).
    SQL> create table phonestuff (phone varchar2(25));
    Table created.
    SQL> insert into phonestuff values ('416.254.6790');
    1 row created.
    SQL> insert into phonestuff values ('1.416.254.6790');
    1 row created.
    SQL> insert into phonestuff values ('416.254.6790 Ext 3217');
    1 row created.
    SQL> insert into phonestuff values ('1.416.254.6790 Ext 3217');
    1 row created.
    SQL> select * from phonestuff;
    PHONE
    416.254.6790
    1.416.254.6790
    416.254.6790 Ext 3217
    1.416.254.6790 Ext 3217
    SQL> commit;
    Commit complete.
    SQL> select rtrim(replace(translate(substr(phone,1,14),'. E','XXX'),'X','')) as fixed
      2  from phonestuff;
    FIXED
    4162546790
    14162546790
    4162546790
    14162546790
    SQL> -Thomas

  • *Silly* SQL Question - SQL Newbie

    Hello,
    Thanks for taking the time reading this.
    Im a SQL Newbie
    Question?
    I Have a PHONE_TABLE, which consist of
    a BUREAU Column and a STATUS Column.
    Within the STATUS column exist 'active' and 'inactive'
    I would like to know if it's possible to create a report that groups a Bureau and counts the # of active /inactive phones
    that displays
    \BUREAU/- - -\Active/ - - - -\Inactive/
    - - - - HR - - - - - 3 - - - - - - - --4 - - - - - - - -
    - - - - IT - - - - - 1 -- - - - -- - - 5 - - - - - - - - -
    - - MGMT - -- -- 3 - - - - -- - - 6 - - - - -- -
    Thanks for the help guys

    Try this:
    select bureau, sum(decode(status,'Active',1,0) ) active , sum (decode(status,'Inactive',1,0) )  inactive
    from PHONE_TABLE
    group by bureauHope this helps!
    Sam
    Please reward good answers by marking them correct or helpful!

  • Question on Dynamic SQL Execution

    Hi,
    Our company is currently using Oracle 7 but will move to Oracle 8i soon. I am trying to execute a dynamic SQL statement in a function and it always error-out during execution. The SQL statement is NOT doing any update to a table. Its doing a select only. The function is being called during an execution of another dynamic SQL statement in a procedure. Here are examples of the code listing for the procedure and function:
    CREATE OR REPLACE PROCEDURE TEST_PROC
    lookup_cursor      integer;
    ignore          integer;
    VARvalue          number;
    begin
    lookup_cursor := DBMS_SQL.open_cursor;
    DBMS_SQL.PARSE( lookup_cursor,
              'SELECT ' || TEST_FUNCTION || ' FROM DUAL,
              DBMS_SQL.NATIVE);
    DBMS_SQL.DEFINE_COLUMN( lookup_cursor, 1, VARvalue);
    ignore := DBMS_SQL.EXECUTE(lookup_cursor);
    loop
         IF DBMS_SQL.FETCH_ROWS(lookup_cursor) > 0 THEN
         DBMS_SQL.COLUMN_VALUE(lookup_cursor, 1, VARvalue);
         ELSE
         EXIT;
         END IF;
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR(lookup_cursor);
    end TEST_PROC;
    CREATE OR REPLACE PROCEDURE TEST_FUNCTION
    lookup_cursor      integer;
    ignore          integer;
    VARvalue          number;
    VARsql_string     VARCHAR2(200);
    begin
    lookup_cursor := DBMS_SQL.open_cursor;
    VARsql_string := SOME GENERATED SQL STATEMENT;
    DBMS_SQL.PARSE( lookup_cursor,
              VARsql_string,
              DBMS_SQL.NATIVE);
    DBMS_SQL.DEFINE_COLUMN( lookup_cursor, 1, VARvalue);
    ignore := DBMS_SQL.EXECUTE(lookup_cursor);
    loop
         IF DBMS_SQL.FETCH_ROWS(lookup_cursor) > 0 THEN
         DBMS_SQL.COLUMN_VALUE(lookup_cursor, 1, VARvalue);
         ELSE
         EXIT;
         END IF;
    END LOOP;
    RETURN VARvalue;
    end TEST_FUNCTION;
    The error I received during execution of TEST_PROC is:
    ORA-06571: Function TEST_FUNCTION does not guarantee not to update database
    ORA-06512: at "SYS.DBMS_SYS_SQL", line 239
    ORA-06512: at "SYS.DBMS_SQL", line 32
    It may seem like the example procedure doesnt need to use a dynamic SQL execution to call TEST_FUNCTION but the actual code that I extracted from does.
    Does Oracle 7 always treat the dynamic SQL command set as some kind of update statement? Is that a bug? I understand that the EXECUTE IMMEDIATE command in Oracle 8i will replace the old command set found in the above examples. Will using the new EXECUTE IMMEDIATE command in Oracle 8i solve this problem?
    Thank you for any help,
    Tony

    In Oracle 7, for a function to be called from a select statement it has to follow the 'purity rule' that it does not modify any database table or package variable.
    Probably you will have to use the compiler directive PRAGMA RESTRICT_REFERENCES (WNDS,WNPS) on your TEST_FUNCTION so that it can be called within a SQL statement.
    This restriction is removed in Oracle 8i onwards.
    Hope this solves your problem.
    Regards

  • Newbie question: ""dynamic"" casting

    Hello all,
    <br>
    I have a quite newbie question. I have this class hierarcy:
    <br>
    A
    |_A1
    |_A2
    |_A3
    |_A4
    |_A5
    |_.....
    <br>
    in some part of my code I have this:
    <br><br>
    if (object1 instanceof A){
    if (object1 instanceof A1)      {A1   object2 = (A1) e;}
              if (object1 instanceof A2)      {A2   object2 = (A2) e;}
              if (object1 instanceof A3)      {A3   object2 = (A3) e;}
              if (object1 instanceof A4)      {A4   object2 = (A4) e;}
              if (object1 instanceof A5)      {A5   object2 = (A5) e;}
    object2.callMethod();
    <br><br>
    Is there any way to do this type of casting just in one line? I mean, I just want to cast object1 to the class it is instanceof. If it is instance of A1, I want to be casted to A1, if it is A2 to A2, etc...
    <br><br>
    Thanks you in advance.

    kamikaze04 wrote:
    In fact I know what object1 is on execution time,Which doesn't help your compiler at all, when it's task to link and verify method calls.
    because the code posted at the top is working well, i just want to avoid repeating that if's for all the new classes Ax I will create. Big "code smell" here.
    In other words if i had from A1 to A200 i dont want to have 200 if's to cast it to the class it is and then execute it's method.You could call the method "doMagic()" and make it abstract in A. Then you can implement it in all Ax classes and would never have to worry about casting in the first place, because A.doMagic() would automagically do the right thing. Polymorphism.

  • 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 and 255 bytes per line limit

    I would like to create a Dynamic SQL statement that is longer than 255 bytes. What do I need to do to embed a carriage return or something so that the resultant string is broken up into multiple lines?

    Please ignore. This was a stupid question!

  • Dynamic SQL and GRANT CREATE ANY TABLE

    hi gurus,
    i have a dynamic SQL in a procedure where a table will be created from an existing table without data.
    strSQL:='create table ' || strTemp || ' as select * from ' || strArc || ' where 1=2';
    execute immediate strSQL;
    without GRANT CREATE ANY TABLE for the user, *"ORA-01031: insufficient privileges"* error during execution.
    Is there a way to tackle this issue without providing GRANT CREATE ANY TABLE privilige?
    many thanks,
    Charles

    ravikumar.sv wrote:
    The problem is not because of dynamic sql...It probably has something to do with dynamic SQL or, more accurately, dynamic SQL within a stored procedure.
    From a SQL*Plus command prompt, you can create a table if your account has the CREATE TABLE privilege either granted directly to it or granted to a role that has been granted to your account. Most people probably have the CREATE TABLE privilege through a role (hopefully a custom "developer role" that has whatever privileges you grant to users that will own objects but potentially through the default RESOURCE role). That is not sufficient to create tables dynamically via a definer's rights stored procedure. Only privileges that are granted directly to the user, not those granted via a role, are visible in that case.
    I expect that the DBAs are granting the CREATE ANY TABLE privilege directly to the account in question rather than through whatever role(s) are being used which is why that appears to solve the problem.
    Justin

  • Dynamic SQL and PL/SQL Gateway

    This question is kind of out of curiosity...I had created a procedure that used some dynamic sql (execute immediate), and was trying to use it on pl/sql gateway. I kept getting page not found errors until I removed the execute immediate statement, and reverted to using static sql statements.
    I am just curious, is dynamic sql not supported at all with pl/sql gateway?
    Thanks
    Kevin

    > Relax damorgan, no need to be condescending. Of course I read the docs ..
    Well, you're one of the few that actually read the docs.. And one of many that lacked to state any real technical details for forum members to understand the actual problem, the actual error, and what the environment is that this is happening in.
    Remember that you came to this forum for forum members to help you. In order for us to do that, you need to help us understand
    - your problem
    - your environment
    - what you have tried
    What PL/SQL Gateway do you refer to? Thus is an old term for an old product - today in Oracle there are two "gateways" into the PL/SQL engine via HTTP. Via Apache/mod_plsql and via the internal Java servlet web engine called EPG inside Oracle.
    As for what the "Gateway" access to the PL/SQL engine via HTTP.. whether it supports EXECUTE IMMEDIATE or not is like asking if a car "supports" soft drinks or not (just because a human that may consume soft drinks acts as the driver of the car). Not sensible or relevant at all.
    mod_plsql creates an Oracle session to the database instance, and executes a PL/SQL procedure in the database. This is no different from any other client connection to Oracle. Oracle has no clue that the client is mod_plsql and not TOAD or Java or VB or PHP or Perl or whatever else.
    So how can this support or not support the EXECUTE IMMEDIATE command? Does PL/SQL support EXECUTE IMMEDIATE? Well duh...
    Why do you get a generic 404? Because the PL/SQL call made by mod_plsql failed with an unhandled exception. mod_plsql gets that exception and now what? Was a valid HTP buffer created for it to stream to the web browser? If the buffer perhaps partially completed? All that mod_plsql knows is that it asked for a HTP buffer via that PL/SQL call and it got an exception in return.
    A 404 HTTP error is the only reasonable and logical response for it to pass to the web browser in this case.
    PS. to see why mod_plsql fail, refer to the access_log and error_log of that Apache httpd server

  • ORA-01008 with ref cursor and dynamic sql

    When I run the follwing procedure:
    variable x refcursor
    set autoprint on
    begin
      Crosstab.pivot(p_max_cols => 4,
       p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
       p_anchor => Crosstab.array('JOB'),
       p_pivot  => Crosstab.array('DEPTNO', 'CNT'),
       p_cursor => :x );
    end;I get the following error:
    ^----------------
    Statement Ignored
    set autoprint on
    begin
    adsmgr.Crosstab.pivot(p_max_cols => 4,
    p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
    p_anchor => adsmgr.Crosstab.array('JOB'),
    p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
    p_cursor => :x );
    end;
    ORA-01008: not all variables bound
    I am running this on a stored procedure as follows:
    create or replace package Crosstab
    as
        type refcursor is ref cursor;
        type array is table of varchar2(30);
        procedure pivot( p_max_cols       in number   default null,
                         p_max_cols_query in varchar2 default null,
                         p_query          in varchar2,
                         p_anchor         in array,
                         p_pivot          in array,
                         p_cursor in out refcursor );
    end;
    create or replace package body Crosstab
    as
    procedure pivot( p_max_cols          in number   default null,
                     p_max_cols_query in varchar2 default null,
                     p_query          in varchar2,
                     p_anchor         in array,
                     p_pivot          in array,
                     p_cursor in out refcursor )
    as
        l_max_cols number;
        l_query    long;
        l_cnames   array;
    begin
        -- figure out the number of columns we must support
        -- we either KNOW this or we have a query that can tell us
        if ( p_max_cols is not null )
        then
            l_max_cols := p_max_cols;
        elsif ( p_max_cols_query is not null )
        then
            execute immediate p_max_cols_query into l_max_cols;
        else
            RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
        end if;
        -- Now, construct the query that can answer the question for us...
        -- start with the C1, C2, ... CX columns:
        l_query := 'select ';
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        -- Now add in the C{x+1}... CN columns to be pivoted:
        -- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
        for i in 1 .. l_max_cols
        loop
            for j in 1 .. p_pivot.count
            loop
                l_query := l_query ||
                    'max(decode(rn,'||i||','||
                               p_pivot(j)||',null)) ' ||
                                p_pivot(j) || '_' || i || ',';
            end loop;
        end loop;
        -- Now just add in the original query
        l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
        -- and then the group by columns...
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        l_query := rtrim(l_query,',');
        -- and return it
        execute immediate 'alter session set cursor_sharing=force';
        open p_cursor for l_query;
        execute immediate 'alter session set cursor_sharing=exact';
    end;
    end;
    /I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
    How do I get it to recognise this?
    Thank you in advance

    Thank you for your help
    This is the version of Oracle I am running, so this may have something to do with that.
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.8.0 - Production
    I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
    Hello, Tom.
    I have one bind variable in a dynamic SQL expression.
    When I open cursor for this sql, it gets me to ora-01008.
    Please consider:
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    JServer Release 8.1.7.4.1 - Production
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1;
      8  end;
      9  /
    declare
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 5
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1, 2;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
    part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
    is ONE bind variable in sql, not two. Is it a bug in 8i?
    What should we do to avoid this error running the same plsql program code on different Oracle
    versions?
    P.S. Thank you for your invaluable work on this site.
    Followup   June 9, 2005 - 6pm US/Eastern:
    what is the purpose of this query really?
    but it would appear to be a bug in 8i (since it should need but one).  You will have to work that
    via support. I changed the type to tarray to see if the reserved word was causing a problem.
    variable v_refcursor refcursor;
    set autoprint on;
    begin 
         crosstab.pivot (p_max_cols => 4,
                 p_query => 
                   'SELECT job, COUNT (*) cnt, deptno, ' || 
                   '       ROW_NUMBER () OVER ( ' || 
                   '          PARTITION BY job ' || 
                   '          ORDER BY deptno) rn ' || 
                   'FROM   emp ' ||
                   'GROUP BY job, deptno',
                   p_anchor => crosstab.tarray ('JOB'),
                   p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
                   p_cursor => :v_refcursor);
    end;
    /Was going to use this package as a stored procedure in forms but I not sure it's going to work now.

  • Insert into using a select and dynamic sql

    Hi,
    I've got hopefully easy question. I have a procedure that updates 3 tables with 3 different update statements. The procedure goes through and updates through ranges I pass in. I am hoping to create another table which will pass in those updates as an insert statement and append the data on to the existing data.
    I am thinking of using dynamic sql, but I am sure there is an easy way to do it using PL/SQL as well. I have pasted the procedure below, and what I'm thinking would be a good way to do it. Below I have pasted my procedure and the bottom is the insert statement I want to use. I am faily sure I can do it using dynamic SQL, but I am not familiar with the syntax.
    CREATE OR REPLACE PROCEDURE ACTIVATE_PHONE_CARDS (min_login in VARCHAR2, max_login in VARCHAR2, vperc in VARCHAR2) IS
    BEGIN
    UPDATE service_t SET status = 10100
    WHERE poid_id0 in
    (SELECT poid_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    DBMS_OUTPUT.put_line( 'Service Status:' || sql%rowcount);
    UPDATE account_t SET status = 10100
    WHERE poid_id0 IN
    (SELECT account_obj_id0 FROM service_t
    WHERE poid_type = '/service/telephony'
    AND login >= min_login AND login <= max_login);
    DBMS_OUTPUT.put_line( 'Account Status:' || sql%rowcount);
    UPDATE account_nameinfo_t SET title=Initcap(vperc)
    WHERE obj_id0 IN
    (SELECT account_obj_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >=min_login AND login <= max_login);
    DBMS_OUTPUT.put_line('Job Title:' || sql%rowcount);
    INSERT INTO phone_card_activation values which = 'select a.status, s.status, s.login, to_char(d.sysdate,DD-MON-YYYY), ani.title
    from account_t a, service_t s, account_nameinfo_t ani, dual d
    where service_t.login between service_t.min_login and service_t.max_login
    and ani.for_key=a.pri_key
    and s.for_key=a.pri_key;'
    END;
    Thanks for any advice, and have a good weekend.
    Geordie

    Correct my if I am wrong but aren't these equal?
    UPDATE service_t SET status = 10100
    WHERE poid_id0 in
    (SELECT poid_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    (update all the records where there id is in the sub-query that meet the WHERE Clause)
    AND
    UPDATE service_t SET status = 10100
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    (update all the records that meet the WHERE Clause)
    This should equate to the same record set, in which case the second update would be quicker without the sub-query.

  • Dynamic SQL Joining between tables and Primary keys being configured within master tables

    Team , Thanks for your help in advance !
    I'm looking out to code a dynamic SQL which should refer Master tables for table names and Primary keys and then Join for insertion into target tables .
    EG:
    INSERT INTO HUB.dbo.lp_order
    SELECT *
    FROM del.dbo.lp_order t1
    where not exists ( select *
    from hub.dbo.lp_order tw
    where t1.order_id = t2.order_id )
    SET @rows = @@ROWCOUNT
    PRINT 'Table: lp_order; Inserted Records: '+ Cast(@rows AS VARCHAR)
    -- Please note Databse names are going to remain the same but table names and join conditions on keys
    -- should vary for each table(s) being configured in master tables
    Sample of Master configuration tables with table info and PK Info :
    Table Info         
    Table_info_ID    Table_Name    
    1        lp_order    
    7        lp__transition_record    
    Table_PK_Info        
    Table_PK_Info_ID    Table_info_ID    PK_Column_Name
    2                1    order_id
    8                7    transition_record_id
    There can be more than one join condition for each table
    Thanks you !
    Rajkumar Yelugu

    Hi Rajkumar,
    It is glad to hear that you figured the question out by yourself.
    There's a flaw with your while loop in your sample code, just in case you hadn't noticed that, please see below.
    --In this case, it goes to infinite loop
    DECLARE @T TABLE(ID INT)
    INSERT INTO @T VALUES(1),(3),(2)
    DECLARE @ID INT
    SELECT @ID = MIN(ID) FROM @T
    WHILE @ID IS NOT NULL
    PRINT @ID
    SELECT @ID =ID FROM @T WHERE ID > @ID
    So a cursor would be the appropriate option in your case, please reference below.
    DECLARE @Table_Info TABLE
    Table_info_ID INT,
    Table_Name VARCHAR(99)
    INSERT INTO @Table_Info VALUES(1,'lp_order'),(7,'lp__transition_record');
    DECLARE @Table_PK_Info TABLE
    Table_PK_Info_ID INT,
    Table_info_ID INT,
    PK_Column_Name VARCHAR(99)
    INSERT INTO @Table_PK_Info VALUES(2,1,'order_id'),(8,7,'transition_record_id'),(3,1,'order_id2')
    DECLARE @SQL NVarchar(MAX),
    @ID INT,
    @Table_Name VARCHAR(20),
    @whereCondition VARCHAR(99)
    DECLARE cur_Tabel_Info CURSOR
    FOR SELECT Table_info_ID,Table_Name FROM @Table_Info
    OPEN cur_Tabel_Info
    FETCH NEXT FROM cur_Tabel_Info
    INTO @ID, @Table_Name
    WHILE @@FETCH_STATUS = 0
    BEGIN
    SELECT @whereCondition =ISNULL(@whereCondition+' AND ','') +'t1.'+PK_Column_Name+'='+'t2.'+PK_Column_Name FROM @Table_PK_Info WHERE Table_info_ID=@ID
    SET @SQL = 'INSERT INTO hub.dbo.'+@Table_Name+'
    SELECT * FROM del.dbo.'+@Table_Name+' AS T1
    WHERE NOT EXISTS (
    SELECT *
    FROM hub.dbo.'+@Table_Name+' AS T2
    WHERE '+@whereCondition+')'
    SELECT @SQL
    --EXEC(@SQL)
    SET @whereCondition = NULL
    FETCH NEXT FROM cur_Tabel_Info
    INTO @ID, @Table_Name
    END
    Supposing you had noticed and fixed the flaw, your answer sharing is always welcome.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

Maybe you are looking for

  • How do I get Vienna Instruments (VI's) into a Logic Project?

    so, I'm running an  IMax OS X 10.6.7, with Logic Pro 9.1.4 I recently downloaded Vienna Symphonic Library Special Edition and Special Edition plus, the latest version.  Everything is now downloaded and ready to go, and I have started messing around w

  • Query 2 tables

    I have created 2 select querys which search a postcode table and then with those results it searchs the solicitors table. I want it to be able to search the solicitors table and also to select all the fees from the fees tbale for each solicitor. So i

  • Dear Experts ,

    i m facing error in idoc to jdbc scenario . when i executed sm58 then showing this error No RFC authorization for function module IDOC_INBOUND_ASYNCHRONOUS  except this everything working fine . please give me solution .

  • Printing a template in pdf @ 100%

    Help I have some templates i need to print and cut out, The templates are bigger than A4 paper, How can i adjust my printer settings so that it prints them at 100% as they are shown in the pdf file ? When i attempt it,i get half the template out on 1

  • Work Center specific Authorization

    Hi all, My specific requirement is we have 7 various plants and each plant having 2 work centers and planner groups like one is for Elect and other is Mech. Now my client wants that particular plant only have the authorization for its particular work