Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if specific column exists in an Access database table

I want to know how to check if a specific column (e.g: date) exists in a specific table(e.g: myTable) in an Access database.

I've read this answer which offers a query which results in another query.

IF NOT EXISTS(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'columnName' 
                AND [object_id] = OBJECT_ID(N'tableName'))
BEGIN
    ALTER TABLE ADD COLUMN MYCOLUMN
END

But what I need is a true/false result.

UPDATE 1

How can I do that in my C# application?

Maybe using SqlCommand.ExecuteScalar() or something else?

like image 586
Alex Jolig Avatar asked Jan 26 '26 10:01

Alex Jolig


1 Answers

As Andre451 mentions in his answer, you can use Access DAO to inspect the Fields collection of the relevant TableDef object, like this:

// test data
string dbFileSpec = @"C:\Users\Public\Database1.accdb";
string tblName = "Clients";
string colName = "LastName";

// COM reference required for project:
// Microsoft Office 14.0 Access Database Engine Object Library
//
var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine();
Microsoft.Office.Interop.Access.Dao.Database db = dbe.OpenDatabase(dbFileSpec);
Microsoft.Office.Interop.Access.Dao.TableDef tbd = db.TableDefs[tblName];
bool colExists = false;
foreach (Microsoft.Office.Interop.Access.Dao.Field fld in tbd.Fields)
{
    if (fld.Name.Equals(colName, StringComparison.InvariantCultureIgnoreCase))
    {
        colExists = true;
        break;
    }
}
db.Close();

Console.WriteLine("Column " + (colExists ? "exists" : "does not exist"));
like image 150
Gord Thompson Avatar answered Jan 27 '26 22:01

Gord Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!