Identify columns after fetching cursor

Hi,
I have a scenario in which iam reading the columns into a cursor and during fetch I want to apply some condition against each column in the cursor.
Eg:
curcor c1 is Select col1,col2,col3 from test;
rec1 c1%rowtype;
begin
open c1;
loop
fetch c1 into rec1;
exit when c1%NOTFOUND;
if rec1.col1=1234
Here instead of using column name can I know that this is the first column in the cursor and apply multiple validations and similarly to next column and so on.
Regards
Satya

If you want to reference columns by position then you either need to be using a ref cursor via a 3rd party developement language like .NET etc. or you need to use the DBMS_SQL package within PL/SQL.
Example of using DBMS_SQL package (from my standard library of examples - in this case something that takes a query and outputs the data as CSV)...
As sys user:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
/As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
                                     ,p_dir IN VARCHAR2
                                     ,p_header_file IN VARCHAR2
                                     ,p_data_file IN VARCHAR2 := NULL) IS
  v_finaltxt  VARCHAR2(4000);
  v_v_val     VARCHAR2(4000);
  v_n_val     NUMBER;
  v_d_val     DATE;
  v_ret       NUMBER;
  c           NUMBER;
  d           NUMBER;
  col_cnt     INTEGER;
  f           BOOLEAN;
  rec_tab     DBMS_SQL.DESC_TAB;
  col_num     NUMBER;
  v_fh        UTL_FILE.FILE_TYPE;
  v_samefile  BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
BEGIN
  c := DBMS_SQL.OPEN_CURSOR;
  DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
  d := DBMS_SQL.EXECUTE(c);
  DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
  FOR j in 1..col_cnt
  LOOP
    CASE rec_tab(j).col_type
      WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
      WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
      WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
    ELSE
      DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
    END CASE;
  END LOOP;
  -- This part outputs the HEADER
  v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
  FOR j in 1..col_cnt
  LOOP
    v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
  END LOOP;
  --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
  UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
  IF NOT v_samefile THEN
    UTL_FILE.FCLOSE(v_fh);
  END IF;
  -- This part outputs the DATA
  IF NOT v_samefile THEN
    v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
  END IF;
  LOOP
    v_ret := DBMS_SQL.FETCH_ROWS(c);
    EXIT WHEN v_ret = 0;
    v_finaltxt := NULL;
    FOR j in 1..col_cnt
    LOOP
      CASE rec_tab(j).col_type
        WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                    v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
        WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                    v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
        WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                    v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
      ELSE
        DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
      END CASE;
    END LOOP;
  --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
    UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
  END LOOP;
  UTL_FILE.FCLOSE(v_fh);
  DBMS_SQL.CLOSE_CURSOR(c);
END;This allows for the header row and the data to be written to seperate files if required.
e.g.
SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
PL/SQL procedure successfully completed.Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno
7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
Adapt to output different datatypes and styles are required.

Similar Messages

  • Is it possible to identify records in ref cursor without actually fetching

    CREATE OR REPLACE PROCEDURE test_miles (p_ref_cursor OUT SYS_REFCURSOR)
    IS
    BEGIN
    OPEN p_ref_cursor FOR
    select 5168 mem_uid, 16353 bac_uid, '2013-JAN-19' dte,3 no_of_pax,'AnoopM' username,NULL reward_id from dual
    union select 4702 mem_uid , 16344 bac_uid, '2013-JAN-29' dte, 2 no_of_pax,'RAZO' username, NULL reward_id from dual;
    END;
    Hi all,
    I have having a Procedure with out parameter as a REF CURSOR.
    This ref cursor will be returned to the calling service.
    Is there a way in oracle by which we can identify whether the Ref cursor holds data without actually fetching it.
    Since if i choose to fetch the data, i will lose one row when i return the ref cursor back to the calling service. Or else is there way i can retrieve the row i lose during fetch.
    Other alternative what have been suggested is create and object type ,fetch the ref cursor values in object type. Then i can use the ref cursor to return the data by table casting.
    one more solution is
    OPEN
    FETCH
    CLOSE
    OPEN (AGAIN)
    In reality the select statement will have is huge lines of code therefore want a suggestion whether there is an alternative to the above solution
    Please suggest.

    CREATE OR REPLACE PROCEDURE test_miles (p_ref_cursor OUT SYS_REFCURSOR)
    IS
    BEGIN
    OPEN p_ref_cursor for SELECT * from DUAL;
    OPEN p_ref_cursor FOR
    select 5168 mem_uid, 16353 bac_uid, '2013-JAN-19' dte,3 no_of_pax,'AnoopM' username,NULL reward_id from dual
    union select 4702 mem_uid , 16344 bac_uid, '2013-JAN-29' dte, 2 no_of_pax,'RAZO' username, NULL reward_id from dual;
    END;
    If the second cursor doesnt fetch any data then an empty dataset will be stored

  • Interoperability problem in fetching cursor b/w oracle 8.1.7 and oracle 9i

    I have got the problem while executing the Fetch
    cursor statement (The statement is used to fetch
    record from the table by using cursor) through PROC
    from Oracle 9i(client) on one m/c to Oracle
    8i(server)version 8.1.7 on the other m/c
    The Operating system is HP-UX 11.0.
    We are getting the Oracle Errno as -932 ie
    "inconsistent datatypes".
    The code is given as follows
    #include <stdio.h>          /* UNIX */
    #include <string.h> /* System include header files */
    #include <stdlib.h>
    EXEC SQL INCLUDE sqlca;
    EXEC SQL begin declare section;
    VARCHAR uid[20];
    VARCHAR pwd[40];
    VARCHAR dbname[40];
    VARCHAR tblname[40];
    char a_szSqlString[1024];
    int h_nCount;          /* balance */
    EXEC SQL end declare section;
    int main()
         strcpy ((char *)uid.arr,"user");
         uid.len=strlen((char *)uid.arr);
         strcpy ((char *)pwd.arr,"pass");
         pwd.len=strlen((char *)pwd.arr);
         strcpy ((char *)dbname.arr,"net1");
         dbname.len=strlen((char *)dbname.arr);
         strcpy ((char *)tblname.arr,"ctltbl");
    tblname.len=strlen((char *)tblname.arr);
         fprintf(stdout," B4 CONNECTING\n");
         fflush(stdout);
         EXEC SQL CONNECT :uid IDENTIFIED BY :pwd USING :dbname;
         fprintf(stdout," AFTER CONNECTING\n");
         fflush(stdout);
         if ( sqlca.sqlcode != 0 )
    printf("Sqlconnect return code = %d\n", sqlca.sqlcode);
    fflush(stdout);
    return;
         fprintf(stdout," AFTER CONNECT STATEMENT\n");
         fflush(stdout);
         sprintf(a_szSqlString, "%s%s%s%s ","select count(*) into :h_nCount from tab "," where TNAME=UPPER('", tblname,"') " );
         EXEC SQL DECLARE sCheckTblName STATEMENT;
         if ( sqlca.sqlcode != 0 )
    printf("Sqlat = %d\n", sqlca.sqlcode);
    fflush(stdout);
    return;
         EXEC SQL PREPARE sCheckTblName from :a_szSqlString;     
         if ( sqlca.sqlcode != 0 )
    printf("Sqlprep = %d\n", sqlca.sqlcode);
    fflush(stdout);
    return;
         fprintf(stdout," AFTER PREPARE STATEMENT\n");
    fflush(stdout);
         EXEC SQL DECLARE cCheckTblName CURSOR FOR sCheckTblName;
         if ( sqlca.sqlcode != 0 )
    printf("Sqldec = %d\n", sqlca.sqlcode);
    fflush(stdout);
    return;
         fprintf(stdout," AFTER CURSOR DECLARE STATEMENT\n");
    fflush(stdout);
         EXEC SQL OPEN cCheckTblName;
         if ( sqlca.sqlcode != 0 )
    printf("Sqlopen = %d\n", sqlca.sqlcode);
    fflush(stdout);
    return;
         fprintf(stdout," AFTER CURSOR OPEN STATEMENT\n");
    fflush(stdout);
         printf("THE VALUE OF COUNT is %d\n",h_nCount);
         EXEC SQL FETCH cCheckTblName INTO :h_nCount;
         if ( sqlca.sqlcode != 0 )
    printf("Sqlfetch = %d\n", sqlca.sqlcode);
    fflush(stdout);
    return;
         fprintf(stdout," AFTER CURSOR FETCH STATEMENT\n");
    fflush(stdout);
         EXEC SQL CLOSE cCheckTblName;
         * If the return code is not ok and first_time is true, no data
         * existed.
         EXEC SQL AT :dbname COMMIT WORK RELEASE;
         /*EXEC SQL COMMIT WORK RELEASE;*/
    The Makefile contents is as follows
    proc sqlcheck=full define=_PROC userid=user/pass@net1 CHAR_MAP=VARCHAR2, DBM
    S=V9 iname=srini1.pc include=/back/app/oracle/rdbms/demo include=/back/app/oracl
    e/plsql/public include=/back/app/oracle/network/public include=/back/app/oracle/
    precomp/public
    cc -g -o sri srini1.c -I/back/app/oracle/precomp/public -I/back/app/oracle/rdbm
    s/demo -I/back/app/oracle/network/public -I/back/app/oracle/plsql/public -I/opt/
    mqm/inc -L/back/app/oracle/lib32 -lclntsh
    Please treat this as an very urgent one!!!!!!!!!!
    V.arunachalam and J.srinivasan

    hi,
    try deleting the into :... from the statement
    that you are parsing as the cursor
    rgds

  • Dynamic Columns in Ref Cursor

    Hi All,
    I have a requirement that i need to execute query having dynamic number of columns using Ref Cursor e.g.
    v_string := 'PO_NUMBER , ORG_ID' ;
    v_query := 'SELECT '|| v_string || 'FROM table_name';
    Can someone please quide me how to define Type dynamically for the above requirement ?
    Thanks
    Vipul Maheshwari

    hope you understand how to use this with the help of ref cursor
    CURSOR Expressions
    A CURSORexpression returns a nested cursor. This form of expression is equivalent to
    the PL/SQL REF CURSORand can be passed as a REF CURSORargument to a function.
    A nested cursor is implicitly opened when the cursor expression is evaluated. For
    example, if the cursor expression appears in a select list, a nested cursor will be
    opened for each row fetched by the query. The nested cursor is closed only when:
    ■ The nested cursor is explicitly closed by the user
    ■ The parent cursor is reexecuted
    ■ The parent cursor is closed
    ■ The parent cursor is cancelled
    ■ An error arises during fetch on one of its parent cursors (it is closed as part of the
    clean-up)
    Restrictions on CURSOR Expressions The following restrictions apply to CURSOR
    expressions:
    ■ If the enclosing statement is not a SELECTstatement, then nested cursors can
    appear only as REF CURSORarguments of a procedure.
    ■ If the enclosing statement is a SELECTstatement, then nested cursors can also
    appear in the outermost select list of the query specification or in the outermost
    select list of another nested cursor.
    ■ Nested cursors cannot appear in views.
    ■ You cannot perform BINDand EXECUTEoperations on nested cursors.
    Examples The following example shows the use of a CURSORexpression in the
    select list of a query:
    SELECT department_name, CURSOR(SELECT salary, commission_pct
    FROM employees e
    WHERE e.department_id = d.department_id)
    FROM departments d
    ORDER BY department_name;
    The next example shows the use of a CURSORexpression as a function argument. The
    example begins by creating a function in the sample OEschema that can accept the
    REF CURSORargument. (The PL/SQL function body is shown in italics.)
    CREATE FUNCTION f(cur SYS_REFCURSOR, mgr_hiredate DATE)
    RETURN NUMBER IS
    emp_hiredate DATE;
    before number :=0;
    after number:=0;
    begin
    loop
    fetch cur into emp_hiredate;
    exit when cur%NOTFOUND;
    if emp_hiredate > mgr_hiredate then
    after:=after+1;
    else
    before:=before+1;
    end if;
    end loop;
    close cur;
    if before > after then
    return 1;
    else
    return 0;
    end if;
    end;
    The function accepts a cursor and a date. The function expects the cursor to be a query
    returning a set of dates. The following query uses the function to find those managers
    in the sample employeestable, most of whose employees were hired before the
    manager.
    SELECT e1.last_name FROM employees e1
    WHERE f(
    CURSOR(SELECT e2.hire_date FROM employees e2
    WHERE e1.employee_id = e2.manager_id),
    e1.hire_date) = 1
    ORDER BY last_name;

  • How to access variable number of columns using ref cursor !

    Hi,
    I am trying to get variable number of columns using ref cursor.
    Declare
    mySzSql varchar2(2000);
    Type dynSqlRC is Ref cursor;
    current_cur dynSqlRC;
    tbl_rec alt_42_consolidated%Rowtype;
    Begin:
    /* This works */
    mySzSql := 'select *
    from
    Table1
    Where
    rowid = ''AAEWNEABXAAAAkxAAA''';
    /* i want something like this to work, this is not working, giving missing variable name error */
    mySzSql := 'select col1, col2, col3
    from
    Table1
    Where
    rowid = ''AAEWNEABXAAAAkxAAA''';
    open current_cur for mySzSql;
    fetch current_cur into tbl_rec;
    close current_cur;
    End;
    I do have the list of desired columns which I am looking to fetch, so after taking that in the record type, how should i get their values. Is it possible to traverse tbl_rec declared above and if column name matches then I will store the value in the array and finally return this array.
    Can somebody please tell me how to do this.
    Thanks

    It appears that this is a followup to How to loop through columns selected by select clause which is itself a followup to [url="
    How to execute dynamic sql"]this earlier thread.
    Assuming these are intended to be followup questions, can we please stick to a single thread? That makes it a lot easier to understand the situation and follow the conversation. Starting multiple threads makes it harder to follow the conversation.
    Thanks,
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Import flat file to multiple tables based on identifier column

    Hello,
    I am trying to setup a package that will import one pipe-delimited flat file (a utility bill) to multiple data tables based on the value of the first column.  I have been told it is similar in format to an EDI file, but there are some differences.
    The number of columns is consistent where the first columns are the same.  Meaning a record that has '00' in the first column will always have 10 columns; a record that has '01' in the first column will always have 9 columns; etc.
    Each value in the first column represents a separate destination data table.  Meaning a record that has '00' in the first column should be output to table '00'; a record that has '01' in the first column should be output to table '01'; etc.  All
    destination tables reside on the same SQL Server.
    Identifier columns can repeat multiple times throughout the flat file.  Meaning a record that starts with '01' may be repeated multiple times in the same.
    Sample Data:
    00|XXXXXXXX|XXX|XXXXXXXX|XXXXXX|XXXX|X|XXXXXXXXXX|XX|XXXXX
    01|XXXXXXXXXXX|XXX|XXXXXXXX|XXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXX|XXXXXXX|XXXXXXXXXXXXXX
    02|XXXXXXXXXXX|XXXXXXXX|XXXXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX
    04|XXXXXXXXXXX|XXXXXXXXXXXXX|XXX|XXXXXXXX
    05|XXXXXXXXXXX|XXXXXXXXXXXXX|XXX|XXXXXXXX|XXXX
    07|XXXXXXXXXXXXX|X|XXXXXXXXXXXXXXX|XXX|XXXXXXXX|XXXX|XXXXXXX|XXXXXXXXXXX
    07|XXXXXXXXXXXXX|X|XXXXXXXXXXXXXXX|XXX|XXXXXXXX|XXXX|XXXXXXX|XXXXXXXXXXX
    07|XXXXXXXXXXXXX|X|XXXXXXXXXXXXXXX|XXX|XXXXXXXX|XXXX|XXXXXXX|XXXXXXXXXXX
    07|XXXXXXXXXXXXX|X|XXXXXXXXXXXXXXX|XXX|XXXXXXXX|XXXX|XXXXXXX|XXXXXXXXXXX
    01|XXXXXXXXXXX|XXX|XXXXXXXX|XXXXX|XXXXXXXXXXXXXXXXXXXX|XXXXXXXXXX|XXXXXXX|XXXXXXXXXXXXXX
    02|XXXXXXXXXXX|XXXXXXXX|XXXXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX|XXXXX
    04|XXXXXXXXXXX|XXXXXXXXXXXXX|XXX|XXXXXXXX
    Any help would be appreciated.

    Hi koldar.308,
    If there are few distinct values in the first column, we can use Flat File Source connect to that flat file, then use Conditional Split Transformation to split the first column to multiples, and then load the data to multiple tables with OLE DB Destination
    based on the outputs of Conditional Split.
    After testing the issue in my environment, please refer to the following steps to achieve this requirement:
    Drag a  Flat File Source connect to that flat file with Flat File Connection Manager.
    Drag a Conditional Split Transformation connects to the Flat File Source.
    Double-click the Conditional Split Transformation, add several Output based on the first column values as below:
    Drag same number OLE DB Destinations as the outputs of Conditional Split, connect to Conditional Split with one case output:
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    If you have any feedback on our support, please click
    here.
    Katherine Xiong
    TechNet Community Support

  • %NOTFOUND - Question on why the EXIT condition is placed right after FETCH

    So i have a procedure that uses a cursor as well as a loop to output the values as follows
    LOOP
    /* Retrieve each row of the result of the above query into PL/SQL variables: */
    FETCH AREA_CUR INTO P_ID, P_LAST_NAME, P_DEPTH;
    /* If there are no more rows to fetch, exit the loop: */
    EXIT WHEN AREA_CUR%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE('Student ID: '||P_ID);
    DBMS_OUTPUT.PUT_LINE('Student Last Name: '||P_LAST_NAME);
    DBMS_OUTPUT.PUT_LINE('Depth: '||P_DEPTH);
    END LOOP;
    Right now, if i were to run my procedure i would get output of
    Schmidt
    Burha
    Which is expected
    But i noticed if i were to switch the EXIT statement to the end just before the end loop i get slightly different results
    LOOP
    /* Retrieve each row of the result of the above query into PL/SQL variables: */
    FETCH AREA_CUR INTO P_ID, P_LAST_NAME, P_DEPTH;
    DBMS_OUTPUT.PUT_LINE('Student ID: '||P_ID);
    DBMS_OUTPUT.PUT_LINE('Student Last Name: '||P_LAST_NAME);
    DBMS_OUTPUT.PUT_LINE('Depth: '||P_DEPTH);
    /* If there are no more rows to fetch, exit the loop: */
    EXIT WHEN AREA_CUR%NOTFOUND;
    END LOOP;
    I then get the results of
    Schmidt
    Buhra
    Burha
    From what I understand after a FETCH statement is issued, it will take the current value of the row its in and then also move to the next line.
    Why would it pick up Burha twice?
    Since the FETCH statement moves to the next line i would expect the output to look more like
    Schmidt
    Buhra
    <Blank> (as this would be the newest line)
    Am i misunderstanding this?

    You are saying that since there is no value to be fetched into variables, then variables in the FETCH stmt should hold NULL values, right? But there is no row (NOT EVEN NULL) to be fetched, therefore variables retain their values.
    And %notfound is a boolean attribute that returns false if the previous fetch returned a row* and true if it didn't, hence we use exit after fetch statement and not at end of loop; Or we may get different results as in your case!
    Mahanam

  • Edit link not working in IE 10 browser after fetching 5000+ rows

    Hi,
    OBIEE 11g 11.1.1.7.150120
    IE 10
    We have an issue where IE browser misbehaves after fetching 5000+ rows.  By misbehaves, I mean the browser responds extremely slow while scrolling up, down, left, right.  Worst behavior is the "Edit" link on the report does not work.  There is no action!  If I navigate to the my home page and try to edit some other report/analysis, same -- no action.  I am able to run other reports but cannot edit any one of them.  Edit link does not work for any report going forward.  If I log-out properly, close the browser window and log back in, only then am I able to edit reports.
    I tried clearing the browser cache several times but this keeps happening.
    This issue is specific to IE only, not Firefox or Chrome. However IE 10 is the corporate browser and switching to any other browser is not a solution.
    Has anybody faced this issue?  Any help in troubleshooting will be greatly appreciated.
    Thanks.

    Hi skull,
    Just to make it simpler ... don't start touching your settings for java heap memory or your account setting to define the default tab when editing an analysis as they have no link with your issue.
    Setting the criteria tab .... well ... as you can't click the edit link you will never get till the criteria tab, so it will not help you a lot (but it's good to set it in case you often edit huge analysis with tons of rows as it doesn't fire a query every time you open it).
    For the java heap memory I can't really see how Chrome or Firefox would behave in a different way on a server side setting like that one.
    So to avoid having multiple other nice issues later don't change settings around without being sure 100% it will have an impact on what you are debugging.

  • Inserting a calculated column after every column in cross tab, in crystal report 2011

    HI,
    I want to insert a calculated column after every column i a cross tab . The cross tab shows , sales by region for a number of years , for example from 2007 to 2013. The year can be changed based on the user parameter. How can I do that ?
    Thanks

    Hi Feroz,
    To calculate the Percentage Change and also to show the Percentage sign, here's what you need to do:
    1) Right-click the Calculated Column Header > Calculated Member > Edit ColumnValue Formula and use this code:
    cdate(1890,01,01)
    If the field used as the column is a datetime field, use this:
    cdatetime(1890,01,01,0,0,0)
    2) Right-click one of the zero values in the Percentage Column and select Calculated Member > Edit Calculation formula and use this code:
    if CurrentColumnIndex  = 2 then 
        If GridValueAt(CurrentRowIndex, CurrentColumnIndex-2, CurrentSummaryIndex) = 0 then 
        0 
        else 
         (GridValueAt(CurrentRowIndex, CurrentColumnIndex-1, CurrentSummaryIndex) - GridValueAt(CurrentRowIndex, CurrentColumnIndex-2, CurrentSummaryIndex))/ 
         GridValueAt(CurrentRowIndex, CurrentColumnIndex-2, CurrentSummaryIndex)
         ) * 100 
    else 
        If GridValueAt(CurrentRowIndex, CurrentColumnIndex-3, CurrentSummaryIndex) = 0 then 
        0 
        else 
         (GridValueAt(CurrentRowIndex, CurrentColumnIndex-1, CurrentSummaryIndex) - GridValueAt(CurrentRowIndex, CurrentColumnIndex-3, CurrentSummaryIndex))/ 
         GridValueAt(CurrentRowIndex, CurrentColumnIndex-3, CurrentSummaryIndex)
         ) * 100 
    3) Right-click one of the Values in the summary cells > Format Field > Number tab > Customize > Currency Symbol tab > Click the formula button beside 'Currency Symbol' and use this code:
    If Year(GridRowColumnValue("Date_field")) = 1890 then
    "%" else "$"
    Note: Replace Date_field with the field name you've used as the Column in the Crosstab. The double-quotes ARE required and you should remove any curly braces that CR adds automatically.
    4) You might want to use a similar code in the 'Position' formula too.
    Let me know how this goes.
    -Abhilash

  • How to Format DataTable Column after load Datatable without extra loop ??

    How to Format Column after load Datatable without extra loop ??
    I dont want to do extra logic which can cause performance thing.
    I have datatable which get fill from Dataset after database query, now i need to format column as decimal but without extra logic.
    I was thinking to create clone and than Import row loop but it ll kill performance, its WPF application.
    Thanks
    Jumpingboy

    You cannot do any custom things at all without doing some "extra logic". Formatting a number as decimal is certainly not a performance killer in any way whatsoever though.
    If you are displaying the contents of the DataTable in a DataGrid you could specify a StringFormat in the XAML:
    <DataGrid x:Name="dg1" AutoGenerateColumns="False">
    <DataGrid.Columns>
    <DataGridTextColumn Header="Number" Binding="{Binding num, StringFormat=N2}"/>
    </DataGrid.Columns>
    </DataGrid>
    Or if you are using auto-generated columns you could handle the AutoGeneratingColumn event:
    public MainWindow() {
    InitializeComponent();
    DataTable table1 = new DataTable();
    table1.Columns.Add(new DataColumn("num")
    DataType = typeof(decimal)
    table1.Rows.Add(1.444444444444);
    table1.Rows.Add(7.444444444444);
    dg1.ItemsSource = table1.DefaultView;
    dg1.AutoGeneratingColumn += dg1_AutoGeneratingColumn;
    void dg1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) {
    if (e.PropertyName == "num") {
    DataGridTextColumn column = e.Column as DataGridTextColumn;
    column.Binding.StringFormat = "N2";
    <DataGrid x:Name="dg1" />
     Please remember to mark helpful posts as answer and/or helpful.

  • How we generate Surrogate Keys without using identify column

    Hi All,
    How we generate Surrogate Keys without using identify column.
    Regards,
    Manish

    There are various options
    1.IDENTITY columns - simplest to implement
    2. Using NEWID(), NEWSEQUENTIALID() functions (if you want to use GUID values as surrogate keys)
    3. SEQUENCE object (if SQL 2012 and above)
    4. Using custom functions to generate keys yourself
    This is an good article which compares use of GUIDs against integers as surrogate keys
    http://blog.jonathanoliver.com/integers-vs-guids-and-natural-vs-surrogate-keys/
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Performace optimization using Fetch  cursor

    Hi All,
    I  want to optimize this code
    IF NOT i_package_data IS INITIAL.
      REFRESH: i_gbfi150000.
      SELECT  *
              FROM /bic/agbfi150000
                      INTO TABLE i_gbfi150000
                      FOR ALL ENTRIES IN i_package_data
                      WHERE  /bic/gsrccocd = i_package_data-/bic/gsrccocd AND
                             /bic/gsrcpctr = i_package_data-/bic/gsrcpctr AND
                             /bic/gsrcjvnd = i_package_data-/bic/gsrcjvnd AND
                             /bic/gsrctpun = i_package_data-/bic/gsrctpun AND
                             /bic/gsrcacct = i_package_data-/bic/gsrcacct AND
                             /bic/gsrcmtyp = i_package_data-/bic/gsrcmtyp AND
                             /bic/gsrcactv = i_package_data-/bic/gsrcactv AND
                             /bic/gsrcfact = i_package_data-/bic/gsrcfact AND
                             /bic/gsrcpcat = i_package_data-/bic/gsrcpcat AND
                             /bic/gsrcf1   = i_package_data-/bic/gsrcf1   AND
                             /bic/gsrcf2   = i_package_data-/bic/gsrcf2   AND
                             /bic/gsrcf3   = i_package_data-/bic/gsrcf3   AND
                             /bic/gsrcf4   = i_package_data-/bic/gsrcf4   AND
                             /bic/gsrcf5   = i_package_data-/bic/gsrcf5   AND
                             /bic/gsrcf6   = i_package_data-/bic/gsrcf6   AND
                             /bic/gsrcf7   = i_package_data-/bic/gsrcf7   AND
                             /bic/gsrcf8   = i_package_data-/bic/gsrcf8   AND
                             /bic/gsrcf9   = i_package_data-/bic/gsrcf9   AND
                             /bic/gsrcf10  = i_package_data-/bic/gsrcf10.
    the internal table i_package data is having 5000 entries so  whn i  am using for all  entries it is taking a lot of time to execute.
    i  am thinking of  fetch cursor technique but am not able to  implement it.kindly help
    regards,
    Sharad

    Moderator message - Please see Please Read before Posting in the Performance and Tuning Forum before posting in the performance and tuning forum
    I don't see how using a cursor would help here at all
    Rob

  • Getting column names from cursor

    Hi all
    I have procedure which produces list of applied for jobs web page(using htp. package)
    I got result in cursor, but have to provide dinamic sort, based on colimn pressed
    procedure my_application_list
    (pi_resume_num     in varchar2 default null
    ,pi_sort_col     in varchar2 default null
    ,pi_page_no     in varchar2 default null
    ,pi_action     in varchar2 default null
    ,pi_msg          in varchar2 default null
    is
    CURSOR cur_job IS
         SELECT      jtl.JOB_TITLE
              ,jtl.COMPANY_NAME
              ,a.APPLY_DATE
              ,a.lang
              ,a.job_id
         FROM job_tl jtl, applied_for_job a, gateway gt
         WHERE a.job_seeker_id=app.job_Seeker
         AND a.job_id=jtl.job_id
         AND a.lang=jtl.lang
         AND a.gateway=gt.gateway
         AND jtl.lang=(SELECT substr(MIN(lt.order_list||jtl0.lang),2) lang
                   FROM      job_tl jtl0
                        ,language_tl lt
                   WHERE jtl0.job_id = a.job_id
                   AND jtl0.lang=lt.lang
                   AND lt.gui_lang=app.language)
         ORDER BY pi_sort_col
    rest of code
    The columns displayed in web page are Job_title, Company_name and Applied_date
    This page is displyed well, bu without column nmes at the top. I am trying to get column names from cursor in order to have ORDER BY <pi_sort_col>
    can someone help how i can get those column names:Job_title, Company_name and Applied_date
    User will be able to click on column and sort
    Thank in advance .I appreciate any help

    Hi Francisco
    Here is my code
    CREATE OR REPLACE PACKAGE BODY cc_web_application_list
    IS
    TYPE COL_NAME_LIST IS TABLE OF VARCHAR2(100)
         INDEX BY BINARY_INTEGER;
    TYPE COL_ORDER_LIST IS TABLE OF VARCHAR2(30)
         INDEX BY BINARY_INTEGER;
    col_name_t col_name_list;
    col_order_t col_order_list;
    procedure my_application_list
         (pi_resume_num     in varchar2 default null
         ,pi_sort_col     in varchar2 default null
         ,pi_page_no     in varchar2 default null
         ,pi_action     in varchar2 default null
         ,pi_msg          in varchar2 default null
    is
    l_my_page_no      PLS_INTEGER :=     TO_NUMBER(nvl(pi_page_no,1));
    l_js_name          gam_user.username%TYPE;
    l_js_first_name          gam_user.first_name%TYPE;
    l_cnt                PLS_INTEGER := 0;
    l_scr_lines      PLS_INTEGER := 0;
    l_curline           PLS_INTEGER;
    l_jobs_applied           PLS_INTEGER;
    l_total_rec      PLS_INTEGER;
    l_total_pages      PLS_INTEGER;
    l_pos               PLS_INTEGER;
    l_first               PLS_INTEGER :=0;
    last                PLS_INTEGER :=0;
    l_lines           PLS_INTEGER := 10;
    col_name      VARCHAR2(100) := col_name_t(3) ;
    col_order           VARCHAR2(30) := 'DESC';
    str                VARCHAR2(2000);
    TYPE display_rec IS TABLE OF VARCHAR2(500) INDEX BY BINARY_INTEGER;
    display           display_rec;
    TYPE page_table_type IS TABLE OF PLS_INTEGER INDEX BY BINARY_INTEGER;
    page_number          page_table_type;
    CURSOR cur_job IS
         SELECT      jtl.JOB_TITLE job_title
              ,jtl.COMPANY_NAME company_name
              ,a.APPLY_DATE apply_date
              ,a.lang
              ,a.job_id
         FROM job_tl jtl, applied_for_job a, gateway gt
         WHERE a.job_seeker_id=app.job_Seeker
         AND a.job_id=jtl.job_id
         AND a.lang=jtl.lang
         AND a.gateway=gt.gateway
         ORDER BY a.apply_date;
    This decode is a problem
              decode(col_order,'ASC'
                   ,decode(col_name
                   ,col_name_t(1), jtl.job_title
                   ,col_name_t(2), jtl.company_name
                   ,col_name_t(3), TO_CHAR(a.apply_date, 'YYYYMMDDhh24miss')
                   ,a.apply_date)
                   ) ASC
              ,decode(col_order,'DESC'
                   ,decode(col_name
                   ,col_name_t(1), jtl.job_title
                   ,col_name_t(2), jtl.company_name
                   ,col_name_t(3), TO_CHAR(a.apply_date, 'YYYYMMDDhh24miss')
                   ,a.apply_date)
                   ) DESC
              ,a.apply_date
    TYPE rec_one IS TABLE OF cur_job%ROWTYPE INDEX BY BINARY_INTEGER;
    r               rec_one;
    BEGIN
    BEGIN
    SELECT username,first_name
    INTO l_js_name,l_js_first_name
    FROM gam_user
    WHERE user_id = App.job_seeker;
    EXCEPTION
    WHEN OTHERS THEN NULL;
    END;
    Cc_Pkg_Elements.p_page_top_job_seeker(
    'Personal Job List'
    ,REPLACE(Txt_Proc_My_Joblist.title_job_list
         ,'##first_name##',l_js_first_name),'N' ,TRUE ,'Pxx');
    ----- get numer of records returned by query
    SELECT COUNT(1)
    INTO l_total_rec
    FROM     job_tl jtl,applied_for_job a
         ,gateway gt
    WHERE a.job_id = jtl.job_id
    AND     a.job_seeker_id     = App.job_seeker
    AND     a.gateway     = gt.gateway ;
    ------get number of pages
    l_total_pages:=CEIL (l_total_rec/l_lines);
    l_jobs_applied := 0;
    col_name := pi_sort_col;
    col_order := pi_sort_col;
    --get first positions
    l_first := (nvl(l_my_page_no,1) - 1) * l_lines + 1;
    FOR rec IN cur_job LOOP
         l_cnt := l_cnt + 1;
         EXIT WHEN l_cnt > l_first + l_lines - 1;
         IF l_cnt >= l_first THEN
              l_scr_lines := l_scr_lines + 1;      
              r(l_scr_lines) := rec;          --assign counter from loop to r index
              IF rec.apply_date IS NOT NULL THEN
              l_jobs_applied := l_jobs_applied + 1;
              END IF;
         END IF;
    END LOOP;
    htp.p('<FORM ACTION="'||App.gateway||'8.my_application_list" METHOD="post">');
    htp.p('<table align="center">');
    htp.p('<tr><td>');
    IF r.COUNT = 0 THEN
         Web_Pkg_Elements.doc_msg(Txt_Proc_My_Joblist.no_jobs);
    END IF;
    htp.p('</td></tr>');
    htp.p('</table>');
    --table_heading(col_name ,col_order );
    htp.p('<table align=center>');
    htp.p('<tr align="center"><td>');
    FOR i IN 1..l_total_pages LOOP
         page_number(i) := i;
         IF page_number(i) = l_total_pages THEN
              htp.p('');
    ||'');
              Web_Pkg_Elements.doc_val_small(page_number(i)||'</A>');          
         ELSE
         htp.p('');
    |'||'');
         Web_Pkg_Elements.doc_val_small(page_number(i)||' |'||'</A>');     
         END IF;
    END LOOP;
    htp.p('</td></tr>');
    htp.p('</table>');
    htp.p('<table align=center>');
    FOR l_curline IN 1..l_scr_lines LOOP
         display(1) := NVL(r(l_curline).job_title, '<br>');
         display(2) := NVL(r(l_curline).company_name, '<br>');
         display(3) := NVL(Cc_Pkg_Nls.date2char(r(l_curline).apply_date, App.date_format), '<br>');
         IF MOD(l_curline, 2) = 0 THEN     
              Cc_Pkg_Elements.tr_even;
         ELSE
              Cc_Pkg_Elements.tr_odd;
         END IF;
         htp.p('<td>');
         htp.p('');
         Web_Pkg_Elements.doc_val(display(1)||'');
         htp.p('</td>');
         htp.p('<td>');
         Web_Pkg_Elements.doc_val(display(2));
         htp.p('</td>');
         htp.p('     <td>');
         Web_Pkg_Elements.doc_val(display(3));
         htp.p('     </td>');
    htp.p('</tr>');
    END LOOP;
    htp.p('</TABLE>');
    htp.p('<TABLE width="88%" BORDER="0" CELLPADDING="0" CELLSPACING="0"
                   align="center">');
    htp.p('<tr valign=bottom>');
    htp.p('<TD colspan=2 align=right>');
    IF l_my_page_no > 1 THEN
         htp.p('<P>'||'<IMG SRC="'||App.image||'prev.gif" ALT="'
         ||Txt_Proc_My_Joblist.prev
         ||'"'     ||' HEIGHT=20 BORDER=0 ALIGN=bottom '
         ||'hspace=2>');
    END IF;
    IF l_my_page_no < CEIL (l_total_rec/l_lines) THEN
         htp.p(' <a href="'||
         web_pkg_elements.link$$(App.gateway||'8.my_application_list?'
         ||'pi_sort_col='||Web_Pkg_Elements.replace_in_url(pi_sort_col)
         ||'&pi_msg=&pi_page_no='||TO_CHAR(l_my_page_no + 1)
         ||">'||'<IMG SRC="'||App.image||'next.gif" ALT="'
         ||Txt_Proc_My_Joblist.NEXT
         ||'"' ||' HEIGHT=20 BORDER=0 ALIGN=bottom '
         ||'hspace=2></a>');
    END IF;
    htp.p('</TD>');
    htp.p('</TR>');
    htp.p('     </TABLE>');
    htp.formHidden('pi_sort_col', pi_sort_col);
    htp.formHidden('pi_page_no', pi_page_no);
    htp.p('</FORM>');
    END my_application_list;
    END ; --cc_pkg_application_list

  • R : Fetch Cursor - Select Cursor

    Scenario I
    - use an OPEN Cursor, Fetch Cursor and specify the MAXROWS parameter as
    200, FORTE returns me only 1 row.About Scenario I: you MUST surround your open-fetch-close cursor cycle by a
    begin transaction - end transaction statement.
    That is, your code should appear as follows:
    begin transaction
    open cursor...
    fetch cursor...
    do what you want...
    close cursor...
    end transaction.
    Hope this helps.
    Greetings.
    Cristina Tomacelli - CSI Piemonte
    Corso Unione Sovietica, 216 - 10134 TORINO - ITALY
    E-mail address: [email protected]
    Telephone Number: +39-11-4618387
    Da: Bala Cuddalore
    A: blunda; chiaberto; tamietti; tomacelli; forte-users
    Oggetto: Fetch Cursor - Select Cursor
    Data: gioved 13 marzo 1997 19.42
    Hi Folks,
    I am using a PREPARE to dynamically create a SELECT statement. when I
    Scenario I
    - use an OPEN Cursor, Fetch Cursor and specify the MAXROWS parameter as
    200, FORTE returns me only 1 row.
    Scenario II
    - use a SELECT using the prepared select statment, the number of rows in
    the Dataset returned by FORTE is 0.
    Am I doing something wrong here ? missing any step? We are running
    on ver 2.0.h.0.
    Any help is greatly appreciated.
    Thanks a bunch,
    Bala Cuddalore
    [email protected]
    Sage Solutions
    1360 Sacramento
    Suite 1360
    San Francisco CA 94111

    I had this problem and solved it by wrapping the OPEN, FETCH, & CLOSE
    cursor statements in an explicit transaction. I'm sure this is related to
    the dialog duration for the dbSession object you are using.
    Dennis Wetzel
    C/Soft, Inc
    Carmel, IN
    Hi Folks,
    I am using a PREPARE to dynamically create a SELECT statement. when I
    Scenario I
    - use an OPEN Cursor, Fetch Cursor and specify the MAXROWS parameteras
    200, FORTE returns me only 1 row.
    Scenario II
    - use a SELECT using the prepared select statment, the number of rowsin
    the Dataset returned by FORTE is 0.
    Am I doing something wrong here ? missing any step? We are running
    on ver 2.0.h.0.
    Any help is greatly appreciated.
    Thanks a bunch,
    Bala Cuddalore
    [email protected]
    Sage Solutions
    1360 Sacramento
    Suite 1360
    San Francisco CA 94111

  • Problem with fetch cursor statement

    Hi,
    I am using FETCH CURSOR statement to fetch the data from a database table with package size. For the fetched records I am doing parallel processing using parallel processing frame work in banking system.
    Here the problem is for the first iteration it works fine but when it comes to FETCH NEXT CURSOR in the second iteration , programs gets dumping by saying that 'CURSOR already closed'.
    I am not closing the cursor in the program but some how it got closed some where in the standard function module which I used for parallel processing.
    I used WITHHOLD also along with FETCH CURSOR but no use. Please let me know how to avoid the cursor to get close.
    Below is my code
    IF NOT l_tab_product IS INITIAL.
        OPEN CURSOR WITH HOLD lv_cursor FOR
         SELECT contract_int prodint cn_currency mig_grp
              INTO TABLE gt_cont
                FROM bca_contract
                FOR ALL ENTRIES IN l_tab_product
                WHERE prodint = l_tab_product-prodint
                AND   mig_grp IN s_migrp.
        DO.
          FETCH NEXT CURSOR lv_cursor
                            INTO TABLE gt_cont
                                 PACKAGE SIZE lv_size.
          IF sy-subrc <> 0.
            CLOSE CURSOR lv_cursor.
            EXIT.
          ELSE.
    parallel processing logic
    ENDDO.
    ENDIF.

    Using Withhold will not make sure that the cursor will not get closed because of commits.
    SAP Doc says
    If the addition WITH HOLD is specified, the database cursor is not closed by a database commit executed using Native SQL. The addition does not have an influence, however, on implicit database commits or on any rollbacks which always close the database cursor.
    You have to check the part written in your parallel processing logic.
    As Brad said please donot dump your old threads like this.

Maybe you are looking for