I need to check if a column exists, can anyone tell me how to do this?
This is in Sql (for a database)
Cheers
Printable View
I need to check if a column exists, can anyone tell me how to do this?
This is in Sql (for a database)
Cheers
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.
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.Quote:
Originally Posted by jmcilhinney