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;

Similar Messages

  • How to re-arrange the columns present in pivot table view in obiee 10?

    Can you please tell me How to re-arrange the columns present in pivot table view in obiee 10?

    I have columns as 1,2,3,4,6,7, in pivot table view.
    I have calculated item (column 5 as summation of 1,2,3,4) and caluclated itme (column 9 as summation of 6,7)...now if i arrange ascending then calculated columns 5,9 don't get affected.
    I need the order as 1,2,3,4,5,6,7,9

  • How can i know the Column Position in a table

    Dear all
    How can i know the Column position in a table ..
    For example :-
    I have a table
    Desc EMPLOYEES
    Empid
    Ename
    Sal
    I want to know the Empid is in 1st position , ename is in 2nd position and sal is in 3rd position .
    is it possible ?

    Hi
    SELECT * FROM ALL_TAB_COLUMNS WHERE
    TABLE_NAME ='EMPLOYEES' AND owner=<OwNeR nAmE> ;)

  • Test whether named column exists in a  view

    hi,
    I need a test, for an if..then else clause to tell me whether there is a column named 'family' in a view.
    Thanks in advance,
    Jon

    Hallo,
    DECLARE
    v_dummy number;
    BEGIN
    select 1 into v_dummy from dual
    where exists (select null from dba_tab_columns
                        where table_name = 'YOUR_VIEW'
                        and column_name = 'FAMILY'
                        and owner = 'YOU');
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
       v_dummy:= 0;
    END;
    IF v_dummy = 1 THEN
    dbms_output.put_line('Column exists');
    ELSE
    dbms_output.put_line('Column doesn't exist');
    END IF;
    Read about dba(all)_objects here
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2005.htm#i1583352
    Regards
    Dmytro
    dbms_output corrected
    Message was edited by:
            Dmytro Dekhtyaryuk                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 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 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.

  • How to check if a constraint existed in the table and drop it?

    Hi all,
    I want to drop a constraint from a table. I do not know if this constraint already existed in the table. So I want to check if this exists first.
    Below is my query:
    DECLARE
    itemExists NUMBER;
    BEGIN
         itemExists := 0;
    SELECT COUNT(CONSTRAINT_NAME) INTO itemExists
    FROM ALL_CONSTRAINTS
    WHERE UPPER(CONSTRAINT_NAME) = UPPER('my_constraint');
    IF itemExists > 0 THEN
    ALTER TABLE my_table DROP CONSTRAINT my_constraint;
    END IF;
    END;
    Here is the error I got when I executed the above query:
    ORA-06550: line 11, column 5: PLS-00103: Encountered the symbol "ALTER" when expecting one of the following: ( begin case declare exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << continue close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe purge
    Please help me with this!
    Greatly appreciate!
    Khoi Le

    Yes, I also tried to put the pl-sql in the Execute Immediate. However, the error still remains
    EXECUTE IMMEDIATE 'DECLARE
    itemExists NUMBER;
    BEGIN
         itemExists := 0;
    SELECT COUNT(CONSTRAINT_NAME) INTO itemExists
    FROM ALL_CONSTRAINTS
    WHERE UPPER(CONSTRAINT_NAME) = UPPER('my_constraint');
    IF itemExists > 0 THEN
    ALTER TABLE my_table DROP CONSTRAINT my_constraint;
    END IF;
    END';
    I execute the above code via running the batch file.
    Here is the error after I ran the batch file:
    ORA-06550: line 11, column 5:
    PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
    ( begin case declare exit for goto if loop mod null pragma
    raise return select update while with <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> <<
    continue close current delete fetch lock insert open rollback
    savepoint set sql execute commit forall merge pipe purge
    The symbol "lock was inserted before "ALTER" to continue.
    ORA-06550: line 11, column 53:
    PLS-00103: Encountered the symbol "DROP" when expecting one of the following:
    . , @ in <an identifier>
    <a double-quoted delimited-identifier> partition subpartition
    ORA-06512: at line 2117
    I can not manually drop it. I need to do this via running an update script file.
    Is there a different way to accomplish this?
    Thank you very much!

  • How to know primary key column name form a table name in sql query

    Suppose I only know the table name. How to get its primary key column name from the table name?
    Thanks

    Views don't have primary keys though their underlying tables might. You'd need to pick apart the view to determine where it's columns are coming from.
    You can select the text of the view in question from user_views.

  • How to not display the column header in the table view?

    I do not want to display the column header in the table view, how can I achieve it?

    If you're using JavaFX 8 you can use the following in an external style sheet:
    .table-view .column-header-background {
      -fx-pref-height : 0 ;
    If you're using JavaFX 2.2, the -fx-pref-height attribute is not available in css, so I think you have to resort to a lookup:
    final Region tableHeader = (Region)table.lookup(".column-header-background");
        tableHeader.setPrefHeight(0);
    As always, I feel obliged to point out that I don't really like lookups. Sometimes they seem to be the only way, though.

  • How to select even the column names of a table?

    Hello All,
    Is there a way to select even the column names of a table in the select statement?
    My select from a table (say X) is in a SQL* Plus script that gets invoked by application tier and displays data in the application tier window. User's can then copy the data into a spreadsheet and do their processing. However, I need to give them the column names too along with the data.
    Thanks,
    Chiru

    If there is a middle tier that is selecting and
    displaying the data, and that's what the users are
    copying from, the middle tier would have to address
    its presentation of the data to allow users to
    include column names. If this is a common task, the
    application should probably be modified to give users
    the option of downloading the data in a spreadsheet
    directly rather than forcing them to copy and paste
    data.Thanks for the reply.
    The users don't have to copy paste. The application tier has an options in the "Tools" menu item which allows them to copy the entire output to a file (in my case a txt file which is a pipe delimited). Then they have to do text to columns to get the data into each column of the spreadsheet. I could have directly called the stored procedures from the application tier and created ".csv" files and FTP'd them to the user's folders. However, I am having to go this round about because, I am not getting enough support from the LAN team in FTP'ing etc.
    OK I'll think of another workaround.
    Thanks,
    Chiru

  • How can i enable a column or field in table control

    hi all,
    i have a table control and in which some column is there, and all are disable mode now my requirement is :
    i want a column enable in this table control with a change button is there.
    so what is the functionality for this change button, if i click this button one of the field is enable i.e in change mode.
    for example- i have 4 fields: in a table control like-
    emp no | name | date| time|
    so i want to enable the field date.if i press the change button
    any one can help me on this, it is very urgent.
    pls send me any code ...if u have.
    thanks,
    vipin

    have  a look at this sample code
    In PAI write :
    CASE sy-ucomm.
      when 'CHANGEBUTTON'.
      Loop at screen.
        IF field1 = 'MATNR'.
          Screen-active = 0.
       endif.
      modify screen.
      endloop.
    endcase.

  • How do I fill a column from a different table

    I am using numbers V3.5 on Yosemite V10.10 and have a question about filling table columns.  I want the new table to ignore some values in the original column.  The first table is a has a matrix of values for multiple stocks and accounts.
    I would like to create a new table for a specific account with only the stocks listed that have a value > $0.  The table would appear something like this.
    I have looked at other posts but could not apply what I have found to this problem.  TIA for any suggestions

    Hi Marty,
    I would suggest you use a filter on your account column- >0 after your bring your data over.
    quinn

  • [help]how to know whether the given column exists in the table or not????

    Hi all, can anyone tell me how to write a C# code help me to know whether the given field exists.
    If it doesnt exists then i want to alter the table to include this column also
    I am able to write the code for alter table but i m not sure how do i check for its existence/nonexistence
    My Altering code
    {color:#800000}cmd.CommandText = "alter table " + row.ToString() + " add(" + sQuality + " varchar2(50), " +
    sTimeStamp + " varchar2(50), " +
    sValue + " varchar2(50))";
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteReader();
    {color}

    Just iterate the datatable after completion and check for your column.
            public static DataTable MaterializeTableStructure(string _connectionString, string _tableName)
                DataSet ds = null;
                using (OracleConnection _oraconn = new OracleConnection(_connectionString))
                    try
                        _oraconn.Open();
                        string sql = "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE FROM user_tab_columns where table_name='" + _tableName + "'";
                        using (OracleCommand cmd = new OracleCommand(sql, _oraconn))
                            cmd.CommandType = CommandType.Text;
                            using (OracleDataAdapter da = new OracleDataAdapter(cmd))
                                ds = new DataSet("MaterializeTableStructure");
                                da.Fill(ds);
                    catch (OracleException _oraEx)
                        throw (_oraEx); // Actually rethrow
                    catch (System.Exception _sysEx)
                        throw (_sysEx); // Actually rethrow
                    finally
                        if (_oraconn.State == ConnectionState.Broken || _oraconn.State == ConnectionState.Open)
                            _oraconn.Close();
                if (ds != null)
                    return ds.Tables[0];
                else
                    return null;
            }r,
    dennis

  • How to test Resource account already exist

    Hi,
    I am creating new createResourceAccount workflow. In my form user enters resource account Id and other information. I want to check, whether given resource acccountId already exist in the resource. If so I would like to display some error in the form. How can I check this. Where as we have to funcionality to test Ligthouse account exist or not.
    My resource is Oracle.
    I appriciate your help.
    thanks
    Neopal.

    Hi vinhant,
    Thanks for your reply. I tried listResourceObjects but it doesn't work. If you have any code sample, could you post it.
    thanks
    Neopal.

  • How to test an image file existing or not

    Hi Everyone,
    I want to test whether an image file exists or not before setting the url of an image component in JSF to it. Following is my code:
    File testFile = new File(image_path + "/p1.jpg");
    if(testFile.exists()){
    info("file exists");
    }else{
    info("file not exists");
    this.myImage.setUrl(image_path+"/p1.jpg");
    Althoug the p1.jpg can be linked to myImage, the existence test always fails. That is, I got the message "file not exists" even though it is already displayed.
    What did I do wrong?
    Thanks in advance,
    Message was edited by:
    field

    File testFile = new File(image_path + "/p1.jpg");Is image_path an absolute path or relative path?

Maybe you are looking for

  • How to use custom nodes in a JTree without reinventing the wheel?

    Hello, Each node contains two JTextAreas in a Box layout and a few JButtons. I wish to display these nodes in a JTree. Reading the tutorial, it seems I would have to reimplement the TreeModel, TreeCellRenderer/Editor, MutableTreeNode interfaces etc.

  • Org unit hierachies

    All, We are using org unit hierachies.  Is it true you can not report on historical data while using org unit hierachies? e.g data is only accurate when we run a report for a current month. Thanks, Nick.

  • CMYK Values in InDesign different to Corel?

    This is probably a stupid question, but.. I had to recreate a document in ID which had been created in Corel Draw, and the CMYK colour values don't seem to translate correctly. For example, a colour in CD has 0,60,60,40 and 153,0,0 RGB.  If I create

  • 2 pdf same view

    Hi, I open 2 PDF. I use Window tiles vertically. So i got the PDF side by side. Is it possbile to navigate in the first PDF and the second PDF in the same thing automatically ex.I rotate the first PDF and put the scale at 25% I want the second PDF do

  • WARNING: \\ hostname \sapmnt\trans\tmp\*. SID already in use (x)

    Hi everybody!! Someone can help me about the next warning when I try to make a transport from QUA to PDC. The transport doesn't pass to PDC envionment. Best Regards The next is the warning: STOP  tp_getprots          PRD P      20071010121848