Results 1 to 3 of 3

Thread: [2008] SqlCommand 'If Column exists'?

  1. #1

    Thread Starter
    Frenzied Member Icyculyr's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    1,934

    [2008] SqlCommand 'If Column exists'?

    I need to check if a column exists, can anyone tell me how to do this?

    This is in Sql (for a database)

    Cheers

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2008] SqlCommand 'If Column exists'?

    You could:

    1. Create an SqlDataAdapter to retrieve all columns from the table, then call FillSchema to create the DataTable schema without actually retrieving the data. You can then test whether the Columns collection contains a column with the desired name.

    2. Create an SqlConnection and call GetSchema, specifying "COLUMNS" as the collection. I'm fairly sure you can specify a table name in the restrictions too to limit the column data returned to just a specific column. That will then fill a DataTable where each DataRow it contains represents a column in the database. You can then test the COLUMN_NAME field of each row to see if your desired column is present.

    That said, it would be a rare thing that you don't know what columns are present in your own database.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: [2008] SqlCommand 'If Column exists'?

    Quote Originally Posted by jmcilhinney
    That said, it would be a rare thing that you don't know what columns are present in your own database.
    Agree. So rare, in fact, that I'd assume the schema is correct and simply handle any exceptions (like you should be doing with SQL operations anyway). If the schema is incorrect, either the user has gone into the database and messed with it, in which case they deserve what they get, or the database has become corrupted somehow, which is an exceptional condition anyway.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width