How to Determine Whether Columns Exist in a Table

Greetings,
Because of customizations to our product, certain database table structures vary between different client installations. Hence, in the code, I need to determine whether two columns exist in a certain table, in order to apply some business logic.
Please suggest a way for me to determine whether two named columns appear in a specific table. In other words, for example, I need to discover whether both columns SAL_GRADE and BONUS appear in the EMP table, or not. Only if both columns are defined, can I apply my business logic.
Thanks,
Avi.

Avi,
Like this ?
SQL> declare
  2    l_count number;
  3  begin
  4    select count(*)
  5      into l_count
  6      from user_tab_columns
  7     where table_name = 'EMP'
  8       and column_name in ('SALGRADE','BONUS')
  9    ;
10    if l_count = 2
11    then
12      dbms_output.put_line('Both columns exist, so apply business logic');
13    else
14      dbms_output.put_line('One or both columns are missing, so don''t apply business logic');
15    end if;
16  end;
17  /
One or both columns are missing, so don't apply business logic
PL/SQL-procedure is geslaagd.Regards,
Rob.

Similar Messages

  • How to check all columns existing in a table?

    Hello.
    I'm writing a function that returns average value of every numeric column existing in a database.
    I have a general idea how to do it, but I need just one more thing, look at the expamle:
    select table_name from user_tables where rownum=1
    this allows me to select names of all tables, and then I can access them 1 by 1...
    But now i have a little problem - how to access all the atributes in selected table in this way?
    Oh, and I have a problem with this rownum... For example it works for 1 (shows 1st row - name of first table) but does not for 2, or greater number :(.
    And expresions like rownum < 5 work, but rownum > 3 not :/. What may be the reason?
    Thank you for help!
    Regards.

    user13483761 wrote:
    Thanks a lot! This 3 atributes is all I need, its a way lot easier than I thought before. I simply use cursor loop and your advices.
    Almost got working code - but there is 1 error telling that select is incorrect :/. Why is that?
    create or replace
    FUNCTION SHOW_ALL
    RETURN VARCHAR2 IS
    v_ret VARCHAR(100):='Null';
    BEGIN
    DECLARE
    CURSOR cur_stats IS SELECT table_name, column_name, data_type
    FROM user_tab_columns;
    v_zdanie VARCHAR(100);
    BEGIN
    FOR v_cur IN cur_stats LOOP
    IF v_cur.data_type = 'NUMBER'
    THEN
    strike
    --> select 'In table ' || v_cur.table_name || ' average value of ' ||--
    --> v_cur.column_name || ' is:' || avg(v_cur.column_name)--
    --> into v_zdanie--
    --> from v_cur.table_name;--
    strike
    >
    dbms_output.put_line(v_zdanie);
    END IF;
    END LOOP;
    RETURN v_ret;
    END;
    END SHOW_ALL;
    select 'In table ' || v_cur.table_name || ' average value of ' ||
    v_cur.column_name || ' is:' || avg(v_cur.column_name)
    into v_zdanie
    from v_cur.table_name;
    sql_developer tells that this 'table or perspective does not exist' or sth like that, I translated from my native language.You are missing lot of things in the function, you are hard coding the return value to null?
    What you should do is as below:
    remove the part what you have written, i have strike that above. declare a variable your_select_statement VARCHAR2(1000);
    your_select_statement := 'select nvl(avg('||v_cur.column_name||'),0) from '||v_cur.table_name;
    execute immediate your_select_statement into v_zdanie;
    dbms_output.put_line('In table ' || v_cur.table_name || ' average value of ' ||v_cur.column_name || ' is:' ||v_zdanie);

  • How to determine whether a recordset is Empty or not ?

    Please see my snippet code below :
    <%     
         String sql="";
         String username="CDS";
         try
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("jdbc:odbc:Employees","","");
                Statement stmt = con.createStatement();
                ResultSet rs=null;
                   sql = "Select * from Employee where code='" + username + "'";
                   rs = stmt.executeQuery(sql);
                   rs.next();
                   if (rs==null)
                   %>
                        <jsp:forward page="Login.jsp?msg=Username not recognized"></jsp:forward>     
                   <%     
                else
                   %>
                        <jsp:forward page="Login.jsp?msg=Halo"></jsp:forward>
                   <%
              catch(ClassNotFoundException e)
                   out.println("Driver not found");
                    catch(SQLException e2)
                            out.println(e2.getMessage());
                            out.println("<BR>");
                            out.println("Wrong SQL Statement");
                            out.println("<BR>");
                            out.println(sql);
                            out.println("<BR>");
         %>How to determine whether a recordset has no result ?
    From the above code, i use if (rs==null) and that's not worked.
    Help me, guys.

    ResultSet rs = stmt.executeQuery(sql);
    if (rs.next()) {
    %>
        <jsp:forward page="Login.jsp?msg=Halo"/>
    <%
    } else {
    %>
        <jsp:forward page="Login.jsp?msg=Username not > recognized"/>
    <%
    }

  • How to test if a column exists in a table

    Hello,
    Using SQL or PL/SQL how do I test if a column exists in a table. For example,
    if column_aa exists in table_1
    then do this....
    else do that....
    Thank you.

    Set ServerOutput On;
    CREATE Table a_Test (
    Col1 NUMBER
    , Col2 NUMBER )
    DECLARE
    lnCol1 NUMBER ;
    lnCol7 NUMBER ;
    PROCEDURE TestColumn( acColName IN VARCHAR2 )
    IS
    lnColX NUMBER ;
    NoColumnExists EXCEPTION;
    PRAGMA EXCEPTION_INIT(NoColumnExists, -904);
    BEGIN
    EXECUTE IMMEDIATE
    'SELECT Max('|| acColName||') FROM a_Test WHERE RowNum = 0'
    INTO lnColX ;
    DBMS_OUTPUT.Put_Line('Column: '||acColName||' exists.');
    EXCEPTION
    WHEN NoColumnExists THEN
    DBMS_OUTPUT.Put_Line('Column: '||acColName||' NOT exists.');
    WHEN Others THEN
    DBMS_OUTPUT.Put_Line( SqlCode ||' '||SqlErrM );
    END
    BEGIN
    DBMS_OUTPUT.Enable ;
    TestColumn( 'Col1') ;
    TestColumn( 'Col2') ;
    TestColumn( 'Col7') ;
    END
    DROP Table a_Test;

  • How to determine whether process Chain is active or Not

    Hello Experts,
    How to determine whether process Chain is active or Not, because i have large number of PC to activate.

    Hi,
    Please check this program in SE38---- /SSA/BWT
    This program will give you information regarding all your process chains which are active and running based on there timings.
    Hope it helps.
    Regards,
    AL

  • How to rename a column name in a table? Thanks first!

    I tried to drop a column age from table student by writing the
    following in the sql plus environment as :
    SQL> alter table student drop column age ;
    but I found the following error
    ORA-00905: &#32570;&#23569;&#20851;&#38190;&#23383; (Lack of Key word)
    I have oracle enterprise edition 8.0.5 installed at windows 2000
    thank you
    And I want to know how to rename a column name in a table?
    thanks

    In Oracle 8i, your syntax would have worked.  However, if I
    recall correctly, in Oracle 8.0, you can't rename or drop a
    column directly.  One way to get around that problem is to
    create another table based on a select statement from your
    original table, providing the new column name as an alias if you
    want to change the column name, or omitting that column from the
    select statement if you just want to drop it.  Then drop the
    original table.  Then re-create the original table based on a
    select statement from the other table.  Then you can drop the
    other table.  Here is an example:
    CREATE TABLE temporary_table_name
    AS
    SELECT age AS new_column_name,
           other_columns
    FROM   student
    DROP TABLE student
    CREATE TABLE student
    AS
    SELECT *
    FROM   temporary_table_name
    DROP TABLE temporary_table_name
    Something that you need to consider before doing this is
    dependencies.  You need to make a list of all your dependecies
    before you do this, so that you can re-create them afterwards. 
    If there are a lot of them, it might be worthwhile to do
    something else, like creating a view with an alias for the
    column or just providing an alias in a select.  It depends on
    what you need the different column name for.

  • How to get the column names of the table into the Dashboard prompt

    how to get the column names of the table into the Dashboard prompt
    Thanks & Regards
    Kishore P

    Hey john,
    My requirement is as follows
    I have created a Rank for Total sales by Region wise i.e RANK(SUM(Dollars By Region)) in a pivot table.
    My pivot table looks like this
    COLUMN SELECTOR: TOTAL US , REGION , DISTRICT , MARKET
    ---------------------------------------------------- JAN 2009          FEB 2009        MAR 2009
    RANK              REGION                  DOLLARS           DOLLARS        DOLLARS DOLLARS
    1 CENTRAL 10 20 30 40
    2 SOUTHERN 10 30 30 70
    3 EASTERN 20 20 20 60
    4 WESTERN 10 20 30 40
    When i select the District in column selector
    Report has to display rank based on Total Sales by District. i.e
    ------------------------------------------------- JAN 2009         FEB 2009       MAR 2009
    RANK             DISTRICT              DOLLARS           DOLLARS        DOLLARS DOLLARS
    for this i need to change the fx of rank i.e RANK(SUM(Dollars By Region)) to RANK(SUM(Dollars By District)) and fx of Region i.e Markets.Region to Markets.District dynamically.
    so , i need to capture column name of the value selected from the column selector and dynamically i need to update the fx 0f RANK & fx of region.
    do you have any solution for this?
    http://rapidshare.com/files/402337112/Presentation1.jpg.html
    Thanks & Regards
    Edited by: Kishore P on Jun 24, 2010 7:24 PM
    Edited by: Kishore P on Jun 24, 2010 7:28 PM

  • How do I restore column headings in Response table after accidently deleting them? Undo doesn't work.

    How do I restore column headings in Response table after accidently deleting them? Undo doesn't work (only seems to go back one level). I also have so many headings I won't be able to type them in manually!

    With the help of information from user, ptressel, in [https://support.mozilla.org/en-US/questions/1032154#answer-673322 a post here about the existence of sessionstore.js when version 33 was released], I was able to easily recover my tabs and tab groups as follows:
    # close Firefox and, perhaps, allow a few seconds (30s?) for any final closing of files;
    # check to see if you have a sessionstore.js file in your profile folder, named like the one I documented in my original post above;
    # if it is not timestamped prior to the discovery of your problem, open the sessionstore-backups folder;
    # check if the recovery.js file is suitably timestamped and, if not, the recovery.bak.
    # At this point, you are likely to find that none of them are prior to your problem occuring. If so, open your backups of this folder and go through steps 2-4 to find a file prior to your problem occuring.
    # When you find a file, copy it to the root of your current profile folder and name it, "sessionstore.js"
    # Open Firefox. Mine opened up as desired.
    This is a Windows solution. Sorry I can't comment on other platforms, but I'd bet that as this is just a file copy and renaming, it is likely the same.
    For Windows users, you may find you need to sign out and login as an administrator in order to access the backups. You need not logoff your standard account, but do have Firefox closed as described above.
    Hope that helps.

  • How to insert select columns from one internal table to another

    Hi,
    How to insert select columns from one internal table to another based on condition as we do from a standart table to internal table.
    regards,
    Sriram

    Hi,
    If your question is for copying data from 1 int table to other ;
    we can use
    APPEND LINES OF it_1 TO it_2.
    or if they have different columns then:
    loop at it_1 into wa_it1.
    move wa_it1-data to wa_it2-d1.
    apped wa_it2 to it_2.
    clear wa_it2.
    endloop.
    thnxz

  • How to determine whether a file doesn't exist or doesn't have enough perms

    Hello everone,
    I am stuck in determining whether a file does not exist or does not have enough permissions so that access to this file is denied?". I am using
    java.io.File.exists() or java.io.File.canRead() methods to check this but both of them just return false in both above mentioned cases.
              In the documentation however its mentioned that these method throw SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file. But then problem is to write a security manager which denies
    read access if the file does not have permissions so that exception can the thrown.
    Any suggestions or pointers will be highly appreciated.
    Thank You.
    Regards,
    Vikash Kumar

    Some platforms will let you rename or remove an open
    file.Unless those platforms support file locking, and the file has a lock on it.

  • How to determine offending column in ORA-01722: invalid number error ...

    When an error like
    ORA-01722: invalid number error
    occurs and you are dealing with many columns that could be the 'culprit', does anyone have a method by which
    you can quickly determine offending column?

    SQL PLus will tell you:
    SQL> create table t
      2  (col1  number
      3  ,col2  number
      4  ,col3  number
      5  ,col4  number
      6  ,col5  number
      7  );
    Table created.
    SQL> create table x
      2  (col1  varchar2(10)
      3  ,col2  varchar2(10)
      4  ,col3  varchar2(10)
      5  ,col4  varchar2(10)
      6  ,col5  varchar2(10)
      7  );
    Table created.
    SQL> insert into x values ('1','2','x','4','5');
    1 row created.
    SQL> insert into t(col1,col2,col3,col4,col5)
      2  select col1,col2,col3,col4,col5 from x;
    select col1,col2,col3,col4,col5 from x
    ERROR at line 2:
    ORA-01722: invalid numberAnd if you rearrange your sql like this, sql plus will give you the line number of the offending column:
    SQL> insert into t
      2  (col1
      3  ,col2
      4  ,col3
      5  ,col4
      6  ,col5
      7  )
      8  select col1
      9        ,col2
    10        ,col3
    11        ,col4
    12        ,col5
    13  from x;
          ,col3
    ERROR at line 10:
    ORA-01722: invalid number

  • How to get only column names from different tables as single table columns

    Hi All,
       I have one requirement in which we want only column names from different tables.
    for example :
     I have three tables T1 ,T2, T3 having
      col1 clo2 clo3 -->  T1 , 
      col3 col5 ,clo6 --> T2 ,
      Clo6 col8 col9 --> T3
    columns i want to get only all  Column names from all table as single Resultset not any data from that how can i get that empty resultset 
    because this empty result i want to bind in datagridview(front end) as Empty resultset 
    Please tell me anyways to do this
    Niraj Sevalkar

    If I understand you want an empty result set, just with metadata. SET FMTONLY do the trick:
    SET FMTONLY ON
    SELECT Col1, Col2, Col3, ....., Coln
    FROM
    T1 CROSS JOIN T2 CROSS JOIN T3
    SET FMTONLY OFF
    Another alternative is to include an imposible contition
    SELECT Col1, Col2, Col3, ....., Coln
    FROM
    T1 CROSS JOIN T2 CROSS JOIN T3
    WHERE 1 = 0
    If you are using a SqlDataAdapter in your client application. You can use the FillSchema method. the select command may be any select statement that returns the columns you want. Under the covers FillSchema will call SET FMTONLY ON.
    If you are using SqlCommand.ExecuteReader you can pass SchemaOnly to CommandBehavior argument. SET FMTONLY ON is called under the covers. Again the select command may be any select statement that returns the columns you want.
    "No darás tropezón ni desatino que no te haga adelantar camino" Bernardo Balbuena

  • How to sum different column in the same table

    Hi everyone
    I would like to know how can I make the sum of different column in the same table using apex
    exple:
    TR_PROJ_BIL_TRIM.ENTPIDFISC as ENTPIDFISC,
        TR_PROJ_BIL_TRIM.EXEANNEE as EXEANNEE,
        TR_PROJ_BIL_TRIM.PROJBILTRIMT1PREV as PROJBILTRIMT1PREV,
        TR_PROJ_BIL_TRIM.PROJBILTRIMT2PREV as PROJBILTRIMT2PREV,
        trunc( TR_PROJ_BIL_TRIM.PROJBILTRIMT1PREV)+(TR_PROJ_BIL_TRIM.PROJBILTRIMT2PREV)
    from TR_PROJ_BIL_TRIM TR_PROJ_BIL_TRIM
    group by TR_PROJ_BIL_TRIM.ENTPIDFISC,TR_PROJ_BIL_TRIM.EXEANNEE
    but while trying to run this script i get this error message:"ORA-00979: not a GROUP BY expression"
    thanks for reading me and I hope to hear from you soon

    Hi,
    Your question do not have anything do with APEX.
    It is pure SQL question and you will get better answer this kind questions from SQL and PL/SQL forum
    You need have GROUP BY when you use aggregate functions like SUM.
    I assume you like just add two columns.
    Try
    SELECT ENTPIDFISC
        ,EXEANNEE
        ,PROJBILTRIMT1PREV
        ,PROJBILTRIMT2PREV
        ,trunc(PROJBILTRIMT1PREV) + (PROJBILTRIMT2PREV)
    FROM TR_PROJ_BIL_TRIM
    Regards,
    Jari

  • How to set initial column widths for a table

    What I'd like to do is to control the initial column widths for a table.
    I'm building the table by using a class which extends AbstractTableModel. This class takes care of setting the headers and reading the data for the table.
    If I do the following:
    VarTableModel vtm = new VarTableModel(vi);
    JTable jt = new JTable(vtm);
    JScrollPane jsp = new JScrollPane(jt);
    frame.getContentPane().add(jsp);
    frame.setVisible(true);
    I will see a table in my window. The widths of the columns are equal and are a function of the horizontal dimension of the window.
    I have tried to set the width of a column by doing the following:
    TableColumn aColumn;
    aColumn = jt.getColumn(vtm.getColumnName(0));
    aColumn.setWidth(40);
    But this has no effect on what gets displayed. I can force the widths that I want by using 'setMaxWidth' but this has the unfortunate side effect of not allowing the user to make the column wider if they want.
    What I'd like is a way to specify the widths of the columns when initially displayed and then let the user adjust to their liking.
    I'm sure that there is a way to do this, but I don't seem to understand where to intervene in the process to produce the effect that I want.
    Any help or suggestions will be greatly appreciated!

    Table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    add this line and try ur codeThanks for the suggestion! Unfortunately, it doesn't seem to do the trick. Here is an abbreviated segment of my code:
    vtm = new VarTableModel(vi);
    JTable jt = new JTable(vtm);
    // we want a horizontal scrollbar, so turn resizing off
    // and we want to control column widths
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    aColumn = jt.getColumn(vtm.getColumnName(0));
    aColumn.setWidth(40);
    . // same kind of thing for each column
    aColumn = jt.getColumn(vtm.getColumnName(4));
    aColumn.setWidth(400);
    JScrollPane jsp = new JScrollPane(jt);
    frame.getContentPane().add(jsp);
    frame.setVisible(true);
    If I do the above, the table gets displayed with each of the five columns the exact same width. So, the sizing of the columns is happening somewhere else despite turning auto resizing off.
    Where is that occurring and how can I intervene so that I can control the widths of the columns on initial display and still allow the user to adjust the widths if they so choose?

  • How To Replace the column data of one table to another table

    Currently I'm Using Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE 11.2.0.1.0 Production
    TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production.
    My Sample Data is,
    create table emp1(ename varchar2(20),deptno number);
    create table emp2(ename varchar2(20),deptno number);
    emp1 Table Data:
    ename deptno
    Surendra 120
    Chandra 180
    Ram 190
    Raj 170
    emp2Table Sample Data:
    ename deptno
    xx 121
    yy 181
    zz 191
    hh 171
    So, My requirement is ,
    How to repalce the ename data of emp1 table into ename of emp2 table .
    My Requred OutPut like:
    select * from emp2;
    ename deptno
    Surendra 121
    Chandra 181
    Ram 191
    Raj 171
    Note:-This is Only Sample data, Actually ,my table haiving more than 1mollions of records.So Performence wise the Query Or Procedure sholud be good.
    Please Help me on this !!
    Thanks in Adv!!

    this ?
    with t as
    select 'Surendra' ename,120 deptno from dual
    union all
    select 'Chandra' ename,180 deptno from dual
    union all
    select 'Ram' ename,190 deptno from dual
    union all
    select 'Raj' ename,170 deptno from dual
    ),t1 as
    select 'xx' ename,121 deptno from dual
    union all
    select 'yy' ename,181 deptno from dual
    union all
    select 'zz' ename,191 deptno from dual
    union all
    select 'hh' ename,171 deptno from dual
    ),t3 as
    select ename,deptno+1 deptno from t
    select t3.ename,t1.deptno from t1,t3 where t1.deptno=t3.deptno;
    ENAME     DEPTNO
    Surendra     121
    Chandra     181
    Ram     191
    Raj     171

Maybe you are looking for

  • I need JDK 1.5.0_8 for 64 bit windows 7

    I need JDK 1.5.0_8 for 64 bit windows 7 Where may I download it?

  • Schedule Job Failed

    I submitted a job using enterprise manager and the job was fail with the error message "VNI-2015 : authentication error". The preferred credentials setting for database is "sys" and for the node is domain administrator. Running Oracle8i and EM2.0 on

  • How to install Acrobat XI pro silently via specific language

    Hi; We sold many acrobat XI pro license, our native language is Turkish but most of our program which is used in our company installation language is English and we want to install Acrobat XI pro via English language setting and we deploy to our clie

  • UWL inbox not rendered properly

    Hi, The UWL inbox in our portal, at times doesnt render properly. The page appears with no proper order of tabs. This problem is not always reproducible. Please help. Regards, Pawan.

  • BP Replication error

    Hi , I have maintained all middleware settings suggested in Best practices and I could successfully replicate BP created in R3 to CRM . But the problem is , BP created in CRM is not replicating to R3 . In SMW01 , I am getting the errors like Error 1