Count of columns in a query

All,
Could anyone please clarify me on , how we can count the column's which were used in a query.
Ex:    SELECT ENAME, EMPNO, SAL , JOB FROM EMP; 
--Here in the above query, I have taken 4 columns(counted manually) . Instead of counting it manually is there any other way.
Thanks

It sounds like you're creating dynamic SQL.  Why are you doing that?  Dynamic SQL's would seem to indicate you don't know the structure of your own database or that your application design is trying to be generic rather than being designed in proper modularized units (1 unit does 1 task, not multiple generic tasks).  99.999% of the time, people using dynamic SQL indicates that they are misusing the database or haven't designed things properly.
If there's really a valid reason for using dynamic SQL, then of course you can do it properly and use all the features of Oracle to get information about the dynamic SQL, but that means not using something as poor as EXECUTE IMMEDIATE (which is often abused by most people), or trying to use ref cursors within PL/SQL (which are more intended for 3rd party application layers).  The power of dynamic SQL is gained from using the DBMS_SQL package... as in the following simplistic example...
SQL> set serverout on
SQL> create or replace procedure run_query(p_sql IN VARCHAR2) is
  2    v_v_val     varchar2(4000);
  3    v_n_val     number;
  4    v_d_val     date;
  5    v_ret       number;
  6    c           number;
  7    d           number;
  8    col_cnt     integer;
  9    f           boolean;
10    rec_tab     dbms_sql.desc_tab;
11    col_num     number;
12    v_rowcount  number := 0;
13  begin
14    -- create a cursor
15    c := dbms_sql.open_cursor;
16    -- parse the SQL statement into the cursor
17    dbms_sql.parse(c, p_sql, dbms_sql.native);
18    -- execute the cursor
19    d := dbms_sql.execute(c);
20    --
21    -- Describe the columns returned by the SQL statement
22    dbms_sql.describe_columns(c, col_cnt, rec_tab);
23    --
24    -- Bind local return variables to the various columns based on their types
25
26    dbms_output.put_line('Number of columns in query : '||col_cnt);
27    for j in 1..col_cnt
28    loop
29      case rec_tab(j).col_type
30        when 1 then dbms_sql.define_column(c,j,v_v_val,2000); -- Varchar2
31        when 2 then dbms_sql.define_column(c,j,v_n_val);      -- Number
32        when 12 then dbms_sql.define_column(c,j,v_d_val);     -- Date
33      else
34        dbms_sql.define_column(c,j,v_v_val,2000);  -- Any other type return as varchar2
35      end case;
36    end loop;
37    --
38    -- Display what columns are being returned...
39    dbms_output.put_line('-- Columns --');
40    for j in 1..col_cnt
41    loop
42      dbms_output.put_line(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
43                                                                                when 2 then 'NUMBER'
44                                                                                when 12 then 'DATE'
45                                                       else 'Other' end);
46    end loop;
47    dbms_output.put_line('-------------');
48    --
49    -- This part outputs the DATA
50    loop
51      -- Fetch a row of data through the cursor
52      v_ret := dbms_sql.fetch_rows(c);
53      -- Exit when no more rows
54      exit when v_ret = 0;
55      v_rowcount := v_rowcount + 1;
56      dbms_output.put_line('Row: '||v_rowcount);
57      dbms_output.put_line('--------------');
58      -- Fetch the value of each column from the row
59      for j in 1..col_cnt
60      loop
61        -- Fetch each column into the correct data type based on the description of the column
62        case rec_tab(j).col_type
63          when 1  then dbms_sql.column_value(c,j,v_v_val);
64                       dbms_output.put_line(rec_tab(j).col_name||' : '||v_v_val);
65          when 2  then dbms_sql.column_value(c,j,v_n_val);
66                       dbms_output.put_line(rec_tab(j).col_name||' : '||v_n_val);
67          when 12 then dbms_sql.column_value(c,j,v_d_val);
68                       dbms_output.put_line(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
69        else
70          dbms_sql.column_value(c,j,v_v_val);
71          dbms_output.put_line(rec_tab(j).col_name||' : '||v_v_val);
72        end case;
73      end loop;
74      dbms_output.put_line('--------------');
75    end loop;
76    --
77    -- Close the cursor now we have finished with it
78    dbms_sql.close_cursor(c);
79  END;
80  /
Procedure created.
SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
Number of columns in query : 4
-- Columns --
EMPNO - NUMBER
ENAME - VARCHAR2
DEPTNO - NUMBER
SAL - NUMBER
Row: 1
EMPNO : 7782
ENAME : CLARK
DEPTNO : 10
SAL : 2450
Row: 2
EMPNO : 7839
ENAME : KING
DEPTNO : 10
SAL : 5000
Row: 3
EMPNO : 7934
ENAME : MILLER
DEPTNO : 10
SAL : 1300
PL/SQL procedure successfully completed.
SQL>

Similar Messages

  • Query to count of Columns??

    How to count the number of columns of a table??
    Thanks in Advance,
    Babjan.

    Ora wrote:
    select count(1) from user_tab_cols where table_name = 'TEMP'
    There is a slight difference between user_tab_cols and user_tab_columns. And user_tab_cols is not suitable for counting table columns:
    SQL> create table tbl(n number)
      2  /
    Table created.
    SQL> select count(*)
      2  from all_tab_cols
      3  where owner = 'SCOTT'
      4  and table_name = 'TBL'
      5  /
      COUNT(*)
             1
    SQL> select count(*)
      2  from all_tab_columns
      3  where owner = 'SCOTT'
      4  and table_name = 'TBL'
      5  /
      COUNT(*)
             1
    SQL> create index tbl_fbi1
      2  on tbl(nvl(n,0))
      3  /
    Index created.
    SQL> select count(*)
      2  from all_tab_cols
      3  where owner = 'SCOTT'
      4  and table_name = 'TBL'
      5  /
      COUNT(*)
             2
    SQL> select count(*)
      2  from all_tab_columns
      3  where owner = 'SCOTT'
      4  and table_name = 'TBL'
      5  /
      COUNT(*)
             1
    SQL> SY.

  • Create custom column in power query

    Hello All,
    I have a requirement to create report for the Analysis, my raw data looks like below which I'm extracting from multiple tables. I would like to extract project wise number count  based on status, my idea is to create custom columns to write the value
    if the value matches to the condition else blank. Example my status has multiple status value ( closed, on-hold,warranty,inprogress,etc) i need to know what formula will help me extract data in different columns so that i can get the count in pivot for each
    status)
    NUMBER         CATEGORY                                Internal SLA  
        EXTERNALSLA      DATE_ENTERED    STATUS
    C1000001    HEINEKEN                                    t             
                     t                  9/13/2014            CLOSED
    C1000002    Migration-BLACKROCK AppV                                                           
    2/11/2015    Terminated
    C1000004    Migration-BLACKROCK AppV                                                          
    10/24/2014    CLOSED
    C1000005    Migration-BLACKROCK AppV        t                                  t  
                  1/12/2015    On-Hold
    C1000006    Migration-BLACKROCK AppV                                                  
             11/5/2014    CLOSED
    C1000007    Migration-BLACKROCK AppV    t                                       
    t               9/12/2014    CLOSED
    C1000008    Migration-BLACKROCK AppV                                                              
    8/6/2014    On-Hold
    C1000009    BLACKROCK                                                                                      
    8/5/2014    In Progress
    C1000010    Migration-BLACKROCK AppV    t                                          t  
                  8/5/2014    On-Hold
    C1000011    Migration-BLACKROCK AppV                                                              
    10/25/2014    CLOSED
    C1000012    BLACKROCK                                                                                        
    9/24/2014    CLOSED
    C1000013    BLACKROCK                                                                                      
    10/16/2014    Terminated
    C1000015    BLACKROCK                                                                                        
    9/1/2014    In Progress

    Hi Imke,
    I have achieved what i wanted to... I did try the way you have suggested. But end result was not fruitful.
    I did following for status wise count.
    Step1: In power query I have created duplicate status column for each status available.( Example I have status {closed,open,initial... etc} I have created duplicate column for each status and replaced with null.For closed Except closed all i replaced in
    column with null).
    Step2: So every time my power query data refreshes it does that step each time so that i can get the count of each status column wise in my pivot table.
    I have attached the result,
    Harsha

  • Multiple Key figure in a single column of a query

    Hi,
    Is it possible to use muliple key figure like Amount and Qty field together in a column of a query?
    Please advise,
    Best Regards,
    UR

    Hi,
    You will be able to do it with the help of cell definitions.
    Say,you have a structure in Rows :
    A
    B
    For A ..in corresponding column cell,use cell definition with KF1
    For B.....in corresponding column cell,use cell definition with KF2
    this way,you will be able to see both in one column
    I m not sure how much it is relavant to your requirement.But this is one way of gettin it

  • Comment column in a query

    Hello,
    In a BW query, I need to add a column of text comments (for example, the description of a calculation, the unit used, ...). These texts are static, the queries will only be used as static reports (download scheduler), in excel and web, so we can not use any VB script.
    Is it a way to add some text in a cell of a column, as in the following example (columns 2 and 3) ?
    KF1    |    Comment for KF1    |    Euros    |    12
    KF2    |    Comment for KF2    |    %          |    47
    Thanks in advance
    Michaë

    Hi guys,
    finally how you fix this problem?, I need to show a comment in a query column and i don't know if this is posible ¿?, I have a query inside of a wad and I want to show a comment in the columns  of the query with the formula details.
    Please let me know if you this is possible.
    Thanks!, Kinds Regards

  • Creating an empty column in a query

    Is there a way to place an empty column in  a query? I would like to put acolumn with no information into the middle of a query. The reason is that the information that goes in that column is not available on any tables in my SQL databases.
    SELECT
    hier.dir_name 
    ,hier.am_name 
    ,hier.fm_name     INSERT BLANK COLUMN HERE
    ,hier.tech_name
    hier.tech_id

    Hi
    "no information" in database is usually NULL value. Is this what you are looking for?
    SELECT
    hier.dir_name
    ,hier.am_name
    ,NULL as fm_name
    --,hier.fm_name INSERT BLANK COLUMN HERE
    ,hier.tech_name
    hier.tech_id
    [Personal Site] [Blog] [Facebook]

  • Access Summary column in a query

    Hi All,
    I am new to oracle reports. I am using report builder 10.1.2.0.2.
    I have a summary column in my report. I would like to use this summary column in another query.
    if is use this column directly in the query, i am getting the below error:
    "Field 'F1' references column '<summary column name>' at a frequency below its group. "
    Both these fields are in the same frame. In the object navigator, both are displayed under the same group name.
    please let me know if there any way to access summary columns in another query.
    Thanks.

    You can use a field from one query in another query as parameter, i.e. preceded by colon. To do this first create link of "Group to Query" type between the first query's group where the summary column is, and the second query.

  • Set Column width in query (not using SQL*Plus)

    How can I Set Column width in query
    I understand you can set column width using
    column col1 FORMAT A5
    select col1 from table1;But this only works in SQL*Plus
    I want to be able to do this in a regular SQL query window (not in SQL*Plus), how can I do it.....
    I am using a 'SQL window' in PL/SQL Developer IDE
    and when I use this syntax it says:
    ORA-00900: Invalid SQL statement
    Any suggestions are appreciated...
    thanks,
    M.

    Did you try using RPAD or LPAD functions? They fill the unfilled part of a string with character you provide... either on right or left side depending on what function you use.
    e.g.
    SELECT RPAD('Smith', 10, ' ') Name FROM dual;http://www.adp-gmbh.ch/ora/sql/rpad.html
    Edited by: Zaafran Ahmed on Nov 10, 2010 11:50 AM

  • Multiple columns from a query sorted vertically

    Is it possible to sort a query resultset vertically, with
    multiple columns across the page, in the following manner, with
    page breaks after 40 rows? I can get it to sort horizontally just
    fine with tables, but how can it be done vertically as shown?
    JONES, Abby JONES, Betty JONES, Dawn JONES, Frank
    JONES, Adam JONES, Bill JONES, Debbie JONES, Gayle
    JONES, Alice JONES, Bob JONES, Denton JONES, Henry
    JONES, Ben JONES, Cathy JONES, Emma JONES, John

    This will get you started. I assume you had the appropriate
    order by clause in your query. I also assume you want 4 columns per
    line.
    My approach would be to convert the query to an array and
    then output the array.
    columns = 4;
    maxrows = 40;
    recordsperpage = columns * rows;
    records = query.recordcount;
    myArray = ArrayNew(2);
    ThisColumn = 1;
    ThisRow = 1;
    if (records gt recordsperpage)
    LoopTill = recordsperpage;
    else
    LoopTill = records;
    for ( ii = 1; ii lte LoopTill; ii = ii + 1){
    myArray[ThisRow][ThisColumn] = query.field[ii];
    increment ThisRow;
    if (ThisRow = MaxRows + 1) {
    ThisRow = 1;
    increment ThisColumn;
    } // if
    } // looop
    You can do the rest

  • Sum of columns in union query

    hi, i am using oracle 10g database..
    how to get the sum of column in union query ?
         select * from (select 100 records from dual), (select 50 available from dual)
    union
    select * from (select 200 records from dual), (select 150 available from dual)
    display should be like
                     records         available
                      100               50
                      200               150
    total            300               200thanks ...

    Peter vd Zwan wrote:
    try this:Grouping by records will not produce correct results:
    SQL> with a as
      2  (
      3  select * from (select 100 records from dual), (select 50 available from dual)
      4  union
      5  select * from (select 100 records from dual), (select 100 available from dual)
      6  union
      7  select * from (select 200 records from dual), (select 150 available from dual)
      8  )
      9  select
    10    case when grouping(records) = 0 then null else 'total' end tot
    11    ,sum(records)   records
    12    ,sum(available) available
    13  from
    14    a
    15  group by
    16  rollup (records)
    17  ;
    TOT      RECORDS  AVAILABLE
                 200        150
                 200        150
    total        400        300
    SQL> select  case grouping(rownum)
      2     when 1 then 'Total'
      3   end display,
      4          sum(records) records,
      5          sum(available) available
      6    from  (
      7            select * from (select 100 records from dual), (select 50 available from dual)
      8           union
      9            select * from (select 100 records from dual), (select 100 available from dual)
    10           union
    11            select * from (select 200 records from dual), (select 150 available from dual)
    12          )
    13    group by rollup(rownum)
    14  /
    DISPL    RECORDS  AVAILABLE
                 100         50
                 100        100
                 200        150
    Total        400        300
    SQL> SY.

  • Set count of column in database......

    hi All,
    i just wanna to ask, it is possible that i can set count of column depends on data/input.
    for example;
    in common, when 2 column, code sql like:
    String query3 = "INSERT INTO Sheet5(Rule, Weight)" + "VALUES ('"+ finalRule+"', '"+weight+"')";but if n column, how?
    anybody knows or give me some idea to handle that..
    thanks.

    what do you means by using preparedStatement?
    is it like this
    String sql1 = "SELECT empno FRom emp WHERE empno = ?";
    String sql2 = "INSERT INTO emp VALUES (?,?,?,?,?,?,?,?)";
    PreparedStatement pstmt1 = conn.prepareStatement(sql1);
    PreparedStatement pstmt2 = conn.prepareStatement(sql2);
    pstmt1.setInt(1, 9999);
    ResultSet rset = pstmt1.executeQuery();
         if(rset.next()){
              System.out.println("The employee");
               rset.close();
         else {
                         pstmt2.setInt(1, 99990);
         pstmt2.setString(2, "CHARLIE");
         pstmt2.setString(3, "ANALYST");
         pstmt2.setInt(4, 7566);
         pstmt2.setString(5, "01-jan-01");
         pstmt2.setFloat(6, 12000);
         pstmt2.setFloat(7, (float)10.5);
         pstmt2.setInt(8, 10);
         pstmt2.executeUpdate();
         }so, i still need to write 8 times '?' for 8 column.
    but how if i don't know count of column?

  • Retrieve varchar column from Oracle query in a resulset

    Hi, I'am a begginer in JSP Technologies.
    I've do a small jsp that opens a db connection to an oracle, execute a query a show results.
    When the columns of the query are int I've no problem, the jsp show the columns of the resulset, but when the columns selected are varchars the jsp doesn't show anything....
    Can anyone help me?
    Example:
    Table: CUSTOMERS
    Col1 : ID_COSTUMER int
    Col2: CUSTOMER_NAME varchar
    <%
    Connection canal = null;
    ResultSet tabla = null;
    Statement instruccion=null;
    try { Class.forName("oracle.jdbc.driver.OracleDriver");
    canal=DriverManager.getConnection("jdbc:oracle:thin:@XXXXXXXXXXXXXXXXXXXp");
    instruccion = canal.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    } catch(java.lang.ClassNotFoundException e){};
    String Query = "SELECT ID_CUSTOMER FROM CUSTOMERS";
    try { tabla = instruccion.executeQuery(Query);
    out.println("<TABLE Border=10 CellPadding=5><TR>");
    out.println("<TD>CUSTOMER</TD></TR>");
    while(tabla.next()) {
    out.println("<TR>");
    out.println("<TD>"+tabla.getString(1)+"</TD>");
    out.println("</TR>"); };
    out.println("</TABLE></CENTER></DIV></HTML>");
    tabla.close(); instruccion.close(); canal.close();}
    catch(SQLException e) {};
    %>Results:
    CUSTOMER
    1
    2
    3
    4
    Doing the change in query:
    SELECT CUSTOMER_NAME FROM CUSTOMERS
    I have not results....
    Thank you.

    sorry, I misplaced an ending code bracket on last one
    I'm not really familiar with doing this inside a jsp.. but there are a few things that you should try to make sure that it isn't a database problem before assuming it is a problem on your jsp.... It is possible you have already tried the following but just to make sure.
    When you do the second query does the first two out.printlns that are before the while still output? If not then your query is incorrect.
    Second I would try
    String Query = "SELECT ID_CUSTOMER,CUSTOMER_NAME FROM CUSTOMERS";
    try { tabla = instruccion.executeQuery(Query);
    out.println("<TABLE Border=10 CellPadding=5><TR>");
    out.println("<TD>CUSTOMER_ID</TD><TD>CUSTOMER_NAME</TD></TR>");
    while(tabla.next()) {
    out.println("<TR>");
    out.println("<TD>"+tabla.getString(1)+"</TD>");
    out.println("<TD>"+tabla.getString(2)+"</TD>");
    out.println("</TR>"); };
    out.println("</TABLE></CENTER></DIV></HTML>");I suspect this will also return nothing.. if that is the case then you need to check your database. If it does infact return values for the ID and nothing for the NAME then I'm not sure at this point what the problem is.

  • How Can i add "DateDiff(day, T0.DueDate" as a column in this query?

    How Can i add "DateDiff(day, T0.DueDate" as a column in this query?
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
          CASE  WHEN T0.TransType=13 THEN 'Invoice'
               WHEN T0.TransType=14 THEN 'Credit Note'
               WHEN T0.TransType=30 THEN 'Journal'
               WHEN T0.TransType=24 THEN 'Receipt'
               END AS 'Document Type',
          T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
          ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
          ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
          ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
          ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
          ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
          ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

    Hi,
    As you mentioned not possible to assign the dynamic column in the query.
    will give you example for generate a dynamic column name in SQL query, using this example you can achieve your requirement.
    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(C.Name) 
                        from [History]
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')
    set @query = 'SELECT [Date],' + @cols +'
                 from
                    select [Date], Name, Value
                    from [History]
                 ) x
                pivot
                    max(value)
                    for Name in (' + @cols + ')
                ) p '
    execute(@query)

  • How to return Parameters values as a column in a query?

    Hi All,
    I have number of parameters in a report.
    I need to return its interred values as a column in a query to use this column in a chart.
    I want this column to be the second one in this query:
    SELECT ROWNUM
    FROM ALL_OBJECTS
    WHERE ROWNUM <= 10
    That is if there is any way to use these parameters directly as a column in the chart no need for the previous statement.
    Note: I am using Reports 6i

    Dear sir
    You can enter parameter as column in query like
    select :parameter p1, &hexadecima_paramataer p2, empcode
    from emps;
    that query make parameter as query column .
    &hexadecimal paramater can refer to database column of table emps
    and :paramater can refer to static string

  • How to implement 'Quick Select' column in a query result table?

    Hi,
    I have a requirement in OAF to design a search page with 'Quick select' column.
    One of the column in the query result table should be a quick select.
    Once user clicks on the quick select column, we have to navigate back to the previous page with the row value selected.
    Can anyone help me in this.
    Thanks.

    Also refer the search exercise in the toolbox tutorials.
    you can implement the quick search in the same way as update and delete buttons.
    --Prasanna                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • Can't see my page in design view, usind split screen

    Hi everyone, I am new to these forums and new to dreamweaver, I have a problem which I have no idea how to fix. I have been using the program (in my limited ability) saved my work, then when I opened it today, I have no design view in Code and Design

  • ITunes corrupted, can't re-install, nor uninstall

    Running Windows XP. I ran a Windows Update the other day, that was titled "Update for XP" or something vague like that. Last night I clicked on iTunes and rather than startup normally, it went into a window that said iTunes was installing....then it

  • How to install the FRMI to Web Server 7.0

    Hi I need a little help, which is like being able to install the service FRMI web server, when the installation made the mistake of telling it not to install the service for the initialization at system start up. How can I add it to boot, Web Server

  • [SOLVED] /media permission denied

    $sudo mount /dev/sda1 /media mount: warning: /media seems to be mounted read-only. $ groups lp wheel games network video audio optical storage power howard trying to mount my music hard drive in /media for audacious. it's ntfs and ide if that makes a

  • Se38 - cannot create program

    Hi, I have another problem [with our company's SAP server].  I cannot create a program even though I am logged into the developer account.  I typed a program name "Z_KEVIN1" and clicked "create."  Here is the error box: Error in Object Editing [in ti