Dynamic column name for Oracle Server Procedure

hello,
May be it's not a right place for my question, but I hope that some of you can help me.
I have source table A that has data of the same kind in 62 fields, let's say employee count for 62 departments. I do some processing with these counts(sum(emp_count) of the same departments for different locations) and store these counts in the variables EC1, EC2, EC3 .. EC62.
Then I need to insert them into my table that has very simple structure let's say table B (dept_no Number(3),
emp_count Number(6))
I want to do a loop and use dynamic colunm EMP_COUNT, something like this:
FOR k in 1..62 LOOP
EMP_COUNT := 'EC'| |k;
IF EMP_COUNT <> O THEN
insert into B
VALUES ( K , EMP_COUNT);
END IF;
END LOOP;
I understand that I need to take a Value of my dynamic colunm EMP_COUNT. Is it possible to do in Oracle Server Procedure? Any idea?
Any help will be apreciated.
null

After having worked in other environments where you can manipulate data records with postitional parameters, Oracle can be frustrating because it demands the explicit use of field names in DML/Select statements. A way around this is to use DBMS_SQL or Dynamic Sql. I have used DBMS_SQL to create and execute dynamic statements with great success. Since you are creating, compiling, and running a dynamic block every time you execute your procedure, this is not recommended except in the rare instances when there is no better way around it.
Oracle8i introduces native dynamic SQL, an alternative to DBMS_SQL. Using native dynamic SQL, you can place dynamic SQL statements directly into PL/SQL blocks.
In most situations, native dynamic SQL can replace DBMS_SQL. Native dynamic SQL is easier to use and performs better than DBMS_SQL.
Example of Dynamic SQL<------------------------
BEGIN
-- bulk fetch the list of office locations
SELECT location BULK COLLECT INTO loc_array
FROM offices;
-- for each location, give a raise to employees with the given 'job'
FOR i IN loc_array.first..loc_array.last LOOP
dml_str := 'UPDATE emp_' &#0124; &#0124; loc_array(i)
&#0124; &#0124; ' SET sal = sal * (1+(:raise_percent/100))'
&#0124; &#0124; ' WHERE job = :job_title';
EXECUTE IMMEDIATE dml_str USING raise_percent, job;
END LOOP;
Look for more information on dynamic SQL by
searching for DBMS_SQL.
Good Luck
null

Similar Messages

  • Dynamic column names in Oracle

    HI SOS!! calling for help...
    i am trying to query the following. I want to remove the duplicates in the ID, and combine them into one... While doing so, I want to keep the data as it is by creating dynamic columns reason_1, reason_2, reason_3 with their corresponding TIME. In case of same reasons, I want to add the TIME. The database is as follows:
    ID     REASON     TIME
    A     41A..........     27
    A     93K..........16
    B     89C...........3
    B     93K...........7
    B     48C..........     4
    C     93K..........     24
    C     93K..........     7
    C     48C.........10
    Expected Result is
    ID     REASON_1......TIME_1.... REASON_2...TIME_2....REASON_3.........TIME_3
    A........ 41A............ 27........... 93K............16          
    B........ 89C............ 3............ 93K............7...........48C.................. 4
    C........ 93K........... 31.......... 48C..............10          
    Would be grateful if someone could try helping me out of this as early as possible.
    Edited by: 968125 on Oct 28, 2012 11:01 PM

    You still haven't made it clear what the requirement is.
    Is there a maximum number of reasons that can occur per ID? If so, you can code the pivoting of your data with something like:
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'A' as ID, '41A' as reason, 27 as time from dual union all
      2             select 'A', '93K', 16 from dual union all
      3             select 'B', '89C', 3 from dual union all
      4             select 'B', '93K', 7 from dual union all
      5             select 'B', '48C', 4 from dual union all
      6             select 'C', '93K', 24 from dual union all
      7             select 'C', '93K', 7 from dual union all
      8             select 'C', '48C', 10 from dual)
      9  --
    10  -- END OF TEST DATA TABLE SIMULATED USING 'WITH' CLAUSE
    11  -- SIMPLY USE THE SELECT STATEMENT BELOW ON YOUR OWN TABLE
    12  --
    13  select id
    14        ,max(decode(rn,1,reason)) as reason_1
    15        ,max(decode(rn,1,time)) as time_1
    16        ,max(decode(rn,2,reason)) as reason_2
    17        ,max(decode(rn,2,time)) as time_2
    18        ,max(decode(rn,3,reason)) as reason_3
    19        ,max(decode(rn,3,time)) as time_3
    20        ,max(decode(rn,4,reason)) as reason_4
    21        ,max(decode(rn,4,time)) as time_4
    22        ,max(decode(rn,5,reason)) as reason_5
    23        ,max(decode(rn,5,time)) as time_5
    24  from (/* assign some row numbers within each ID, ordering by 'reason' then 'time' */
    25        select id, reason, time
    26              ,row_number() over (partition by id order by reason, time) as rn
    27        from   t
    28       )
    29* group by id
    SQL> /
    I REA     TIME_1 REA     TIME_2 REA     TIME_3 REA     TIME_4 REA     TIME_5
    A 41A         27 93K         16
    B 48C          4 89C          3 93K          7
    C 48C         10 93K          7 93K         24In this example, it will cater for up to 5 reasons/times per ID... and you can code for more if you need very easily.
    Also, as you're using 11g, you can use the new PIVOT query, for which you can find plenty of examples if you google or search these forums, or follow the FAQ link.
    If you don't have any idea how many reasons there could be, then you really are looking at generating columns dynamically.
    The problem with that is, because Oracle needs to know the SQL projection (see the FAQ link already provided), it has to know how many columns are going to be returned from a query before any data is fetched... but you are saying that the columns returned have to be based on the data itself. To do that you have two main options:
    1) You query the data once to determine how many columns you are going to need and then dynamically build up a query in PL/SQL code with the right number of columns (or use one of the other dynamic methods shown in the FAQ)
    or
    2) You step back and ask yourself if SQL is really the best place to be trying to produce this output. Reporting tools are often better suited to this requirement as they are made to query the data back from a database and then pivot and layout the data based on the data returned.

  • Need to return dynamic column names for a function returning nested table

    I am having a pl/sql function which is returning a nested table.
    For this i have defined an object which is having 4 attributes- 1 number type, 3 varchar2 type -p1,p2,p3.
    My function is taking input parameter v1,v2,v3 all of varchar2 type.Inside the function body,i am using these (v1,v2,v3) to filter data from an sql query and i am also
    using pivot function in this sql query.
    At the end my function is returning the object as defined in the starting .
    When i am excuting this function,thru select statement :
    select * from table(f1_test('A','B','C'));
    i am geting p1,p2,p3 as column name ,which are names used when i had defined object type.Instead i want column name to be dynamic (wotever i am passing in function as
    parameter while executing the function ,here A,B,C)
    Please help me in geting column names dynamic as passed in input parameter (i.e A,B,C for this case )
    Sample code for the problem:
    create or replace TYPE obj1 AS OBJECT
    ( id number(5,0)
    ,p1 varchar2(10),
    ,p2 varchar2(10)
    ,p3 varchar2(10)
    create or replace TYPE tt1 AS TABLE OF OBJ1;
    create or replace
    function f1_test (v1 varchar2,v2 varchar2,v3 varchar2)
    return tt1 as
    v_return tt1 ;
    v_str varchar2(30000);
    begin
    v_str:='
    select
    cast(
    multiset(
    select * from
    select
    aa.report_id
    ,cc.name
    ,e.amount
    from
    aa,cc,e
    where
    <join conditions>
    and cc.name in ('''||v1||''','''||v2||''','''||v3||''')
    pivot (sum (amount) for name in ('''||v1||''' as '||v1||','''||v2||''' as '||v2||','''||v3||''' as '||v3||'))
    as tt1)
    from
    dual';
    dbms_output.put_line(v_str);
    execute immediate v_str
    into
    v_return ;
    return v_return;
    end;
    Edited by: 845831 on 20 Mar, 2011 12:15 PM

    select id,p1 A,p2 B,p3 C from table(f1_test('A','B','C'));
    drop function f1_test;
    drop type tt1;
    drop type obj1;
    create or replace TYPE obj1 AS OBJECT
    ( id number(5,0)
    ,p1 varchar2(10)
    ,p2 varchar2(10)
    ,p3 varchar2(10)
    create or replace TYPE tt1 AS TABLE OF OBJ1;
    CREATE OR REPLACE
      FUNCTION f1_test(
          v1 VARCHAR2,
          v2 VARCHAR2,
          v3 VARCHAR2)
        RETURN tt1
      AS
        v_return tt1 ;
        v_str VARCHAR2(30000);
      BEGIN
        v_str:='select cast(multiset(select 1,''20'',''30'',''40'' from dual) as tt1) from dual';
        dbms_output.put_line(v_str);
        EXECUTE immediate v_str INTO v_return ;
        RETURN v_return;
      END;
    /

  • Need to know base table and base column name for Oracle view columns

    I am trying to load metadata for some views and that requires me to know what the final table and column name would be corresponding to the view column.
    For example, if I have a view x_v that is select a,b from x_v2; and x_v2 is a view that is select a,b,c from x;
    I need to get the following information.
    View View Col Base Table Base Col
    X_V A X A
    X_V B X B
    and so on.
    Is it possible to get this programmatically using any SYS schema tables or Dependency tables?
    I tried an indirect approach wherein I lock tables using LOCK TABLE or FOR UPDATE OF. But I'm not too sure if I can go down to the level of individual view columns.
    Can you help me with this?

    Thanks. I was looking at some indirect approaches.
    I came up with this script that does it faster than dependencies but thats just for tables and not column mapping.
    declare
    cursor bt(cp_sid number) is
    select u.name uname, o.name oname
    from sys.obj$ o, sys.user$ u
    where o.obj# in (select id1
    from v$lock
    where sid=cp_sid)
    and u.user# =o.owner#;
    cursor c_sid is
    select sid
    from v$session
    where audsid =userenv('sessionid');
    l_sid number;
    l_view varchar2(100):= 'PER_PEOPLE_V';
    l_schema varchar2(10):= 'APPS';
    begin
    open c_sid;
    fetch c_sid into l_sid;
    close c_sid;
    dbms_output.put_line('SID: '||l_sid);
    execute immediate 'lock table '||l_schema||'.'||l_view||' in row share mode nowait';
    for i in bt(l_sid) loop
    dbms_output.put_line(i.uname||'.'||i.oname);
    execute immediate 'alter table '||i.uname||'.'||i.oname||' disable table lock';
    execute immediate 'alter table '||i.uname||'.'||i.oname||' enable table lock';
    end loop;
    end;
    It basically uses locks on views to verify locks on the base tables.
    Just wondering, can we use FOR UPDATE OF statements to get to the columns?

  • How to change recordset bahaviour to accept dynamic column names in the where clause

    Hi
    im using php-mysql and i make a recordset and i want to make the column names in the where clause to be dynamic like
    "select id,name from mytable where $tablename-$myvar";
    but when i do this my i break the recordset and it disappear
    and when i use variables from advanced recordset it only dynamic for the value of the column not for the column name
    and when i write the column name to dynamic as above by hand it truns a red exclamation mark on the server behaviour panel
    so i think the only way is to change the recordset behaviour is it? if so How to make it accept dynamic column names?
    thanks in advance.

    As bregent has already explained to you, customizing the recordset code will result in Dreamweaver no longer recognizing the server behavior. This isn't a problem, but it does mean that you need to lay out your dynamic text with the Bindings panel before making any changes. Once you have changed the recordset code, the Bindings panel will no longer recognize the recordset fields.
    Using a variable to choose a column name is quite simple, but you need to take some security measures to ensure that the value passed through the query string isn't attempting SQL injection. An effective way of doing this is to create an array of acceptable column names, and check that the value matches.
    // create array of acceptable values
    $valid = array('column_name1', 'column_name2', 'column_name3');
    // if the query string contains an acceptable column name, use it
    if (isset($_GET['colname']) && in_array($_GET['colname'], $valid)) {
      $col = $GET['colname'];
    } else {
      // set a default value if the submitted one was invalid
      $col = 'column_name1'
    You can then use $col directly in the SQL query.

  • Saving result from sp_executesql into a variable and using dynamic column name - getting error "Error converting data type varchar to numeric"

    Im getting an error when running a procedure that includes this code.
    I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
    DECLARE @retval AS DECIMAL(12,2)
    DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
    DECLARE @sqlcmd AS NVARCHAR(150)
    DECLARE @paramdef NVARCHAR(150)
    SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
    SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
    SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
    SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
    --default
    SET @retval = 0.0;
    EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
    SELECT @retval
    DECLARE @return_value DECIMAL(12,2)
    EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
    @SpreadKey = 1,
    @MonthNumber = 4
    SELECT 'Return Value' = @return_value
    Msg 8114, Level 16, State 5, Line 1
    Error converting data type varchar to numeric.

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
    This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
    the shoe size, the phone number or something else at run time of this entity. 
    In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point. 
    Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity. 
    Do you know that SQL is a declarative language? This family of languages does not use local variables! 
    Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.  
    Think about how silly this is: 
     SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
    We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental. 
    We need to see the DDL so we can re-write this mess. Want to fix it or not?
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to rename the column name in oracle 8i?

    hi,
    Does anyone know how to rename the column name in oracle 8i?My method was drop the relationship key first then delete the old column,finally add the new column.
    Thanks for your replay.
    jing

    There is no facilty to rename a column name in Oracle 8i. This is possible from Oracle 9.2 version onwards.
    For you task one example given below.
    Example:-
    Already existed table is ITEMS
    columns in ITEMS are ITID, ITEMNAME.
    But instead of ITID I want ITEMID.
    Solution:-
    step 1 :- create table items_dup
    as select itid itemid, itemname from items;
    step 2 :- drop table items;
    step 3 :- rename items_dup to items;
    Result:-
    ITEMS table contains columns ITEMID, ITEMNAME

  • How to change the name / IP address and domain name for BOE Server

    Hello,
    We want to change the name / IP address and domain name for BOE Server, please could you indicate the steps or procedure to follow?
    I need your help
    thank you

    If it's 3.1 just change them, shouldn't cause any issues if by domain name you are referring to changing the domain the computer belongs to. If you are changing your domain for AD authentication then you will may have to take quite a few steps if the old domain is going away. Let us know.
    Regards,
    Tim

  • Dynamic column name sql?

    I need to do a select statement using dynamic column names. Can it be done WITHOUT building a string to execute the sql?
    In other words, I want to use a variable name in the SELECT part of a statement.
    Thanks

    Properly done, there shouldn't be a great difference in the performance of static and dynamic SQL. Of course, dynamic SQL is a whole lot more complicated to get right. It's also rather at odds with your requirement that column names get passed in dynamically-- if you don't know what columns you're going to select at compile time, you can't use static SQL.
    That said, there are a handful of tricks around using Oracle's built-in XML processing functionality to simulate dynamic SQL. This is almost certainly less efficient than doing dynamic SQL in your case, and a whole lot more complicated, but it's technically not dynamic SQL.
    The proper response, though, is almost certainly to either
    1) figure out how to design the application so that column names need not be passed in at runtime or
    2) use dynamic SQL.
    If at all possible, option 1 is generally preferable. While there are situations where dynamic SQL is necessary, those tend to be rather rare.
    Justin

  • How to change IP, Hostname and domain name for Oracle Application R12

    Hi,
    I'm new to Oracle, we used to have one production and one test server for Oracle Application R12, but the test server was corrupted, so we decided to clone production server and create a new test server, after cloning and creation of test server, how should we do to change IP address, hostname and domain name for test server?
    Our production and test server environment is:
    Linux Enterprise AS 2.6.9
    Application module: E-Business Suite Treasury only
    Your advice will be much appreciated.
    Regards,
    Kenneth
    Edited by: 850209 on Apr 7, 2011 5:37 PM

    850209 wrote:
    Hi,
    There are few tnsnames.ora and listener.ora files in the system, how to know which one are effective? If I change tnsnames.ora hostname entry, do I need to change listerner.ora file also?
    Thanks.
    Regard,
    Kenneth.tnsnames.ora is used only by client processes. listner.ora is used only to configure the listener, and that is a server side issue only. In addition, the listener can start without any listener.ora at all, using all default values. See my discussion of tns issues at edstevensdba.wordpress.com
    If you are using dbcontrol, you will most likely need to reconfigure it, using the emca utility.

  • How to get column names for a specific view in the scheme?

    how to get column names for a specific view in the scheme?
    TIA
    Don't have DD on the wall anymore....

    or this?
    SQL> select text from ALL_VIEWS
      2  where VIEW_NAME
      3  ='EMP_VIEW';
    TEXT
    SELECT empno,ename FROM EMP
    WHERE empno=10

  • What are the userid,password, and host name for oracle 9i?

    HI Guys.
    I am a research student at the University and the I recently downloaded Oracle 9i for my research. But the problems is also with seting it up. Please could you show me the userid, password, and host name for oracle 9i.
    Thanks in advance for your cooperations.
    Malinga R
    [email protected]

    I believe that starting with 9.2, you have to specify different passwords when you install (can't be the default).
    Justin

  • [Flat File Destination [220]] Error: Failed to write out column name for column "Column 2"

    I am using SSIS to extract fixed width data into a flat file destination and I keep getting below error. I have tried almost everything in this forum but still no solution. can anyone help me out to solve this problem.
    [Flat File Destination [220]] Error: Failed to write out column name for column "Column 2".
    [SSIS.Pipeline] Error: component "Flat File Destination" (220) failed the pre-execute phase and returned error code 0xC0202095
    Thanks

    Hi Giss68,
    Could you check the Advanced tab of the Flat File Connection Manager to see whether the InputColumnWidth and the OutputColumnWidth properties of the Column2 has the same value? Please refer to the following link about the same topic:
    http://stackoverflow.com/questions/10292091/how-do-i-fix-failed-to-write-error-while-exporting-data-to-ragged-right-flat-fil 
    If it doesn’t work, please post the sample data and the advanced settings of Column2 for further analysis.
    Regards,
    Mike Yin
    If you have any feedback on our support, please click
    here
    Mike Yin
    TechNet Community Support

  • Finding source database table/column name for a column in a view

    Hi i need to be able to identify the original database table/column name for a column in a view.
    e.g. say i have a view like this
    create v1 as select a.name fname, b.name bname, c.name cname,......
    from u1.names a, u2.names b. u3.names c
    where .....
    Now I want to find out that the database table/column name for the fname, bname and cname columns in the view v1, which in this instance is u1.name.name, u2.names.name, u3.names.name.
    But i need to be able to do it for any view. Short of parsing the SQL is there an easy way of doing this?
    Now obviusly I can't do this for virtual columns but I will know my column is not virtual as it has an index on it.

    But i need to be able to do it for any view. Short of
    parsing the SQL is there an easy way of doing this?No, parsing the SQL is the only way. Good luck it is not something I would want to attempt.

  • Form with dynamic Column Names

    Hello,
    I am using "Form with report on table" and I would like to make use of dynamic column names labels that are derived from another table (sql). I am stuck on how to do this, any advice?

    Hi FourEyes;
    Try using this.
    Select Col1, Col2, Col3
    into :P1_Field1, :P1_Field2, :P1_Field3
    from Your_Table
    Where (your conditions);

Maybe you are looking for

  • Problem in launching ESR with JWS

    Hi, Im trying to launch ESR and ID for the first time for PI sandbox. ID launches just fine, but ESR results in error. I tried clearing cache, didnt help. I'm using Java 1.6 Here is the exception I get. java.lang.reflect.InvocationTargetException    

  • Enable Business Objects in Enterprise into Services

    Dear all, environment : Enterprise Portal / mySAP ERP 2005 / Visual Composer. I would like to use e.g. List Order Fulfilment ( a BO in the pcd) PCD location : pcd:Business_Objects/com.sap.pct.erp.common Object type : com.sapportals.portal.businessobj

  • SOA server Memory fault

    Hi , we got the following error from SOA server <Oct 1, 2013 11:46:12 PM EET> <Warning> <JTA> <BEA-110486> <Transaction BEA1-4D0912FE2D411AD3416B cannot complete commit processing because resource [FNViewDS_soadomain] is unavailable. The transaction

  • Can I use Imovie 6 to combine edit songs and combine them?

    I would like to import some songs, cut some of them in half, and make them into one big song.  Can I use iMove or is there a better free program for that?

  • Anchoring multiple Guest SSIDs to the same WLC

    Hi All, I've currently got a typical 'anchored' Guest WLAN solution where several WLCs tunnel guest traffic back to an isolated WLC for WebAuth - this all works fine using a mix of 5508 / 4400, all on v7.0.98.0 code. The question is, can I add a seco