Click here to Skip to main content
15,867,190 members
Articles / Programming Languages / Visual Basic
Article

Check if a table or field exists in a database

Rate me:
Please Sign up or sign in to vote.
4.19/5 (13 votes)
13 Nov 2008CPOL 186K   38   13
Function to check if a table or field exists in an MS Access or SQL Server database.

Introduction

These are two functions I wrote in VB.NET using ADO.NET to check and see if a table or a field exists in a database. It can work with MS Access, or SQL Server, or any other OLE database.

Background

Checking if a table or a field exists in an Access database should be a very simple task, but it can become very complicated with ADO.NET. With DAO or ADO in VB 6.0, this was an extremely easy task. Those who have used it will agree. So, I am posting these functions to help other programmers. Hopefully, it will help out some.

Using the code

Here are the functions:

VB
''' <summary>
''' Checks to see if a table exists in Database or not.
''' </summary>
''' <param name="tblName">Table name to check</param>
''' <param name="cnnStr">Connection String to connect to</param>
''' <returns>Works with Access or SQL</returns>
''' <remarks></remarks>

Public Function DoesTableExist(ByVal tblName As String, ByVal cnnStr As String) As Boolean
    ' For Access Connection String,
    ' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
    ' accessFilePathAndName

    ' Open connection to the database
    Dim dbConn As New OleDbConnection(cnnStr)
    dbConn.Open()
    
    ' Specify restriction to get table definition schema
    ' For reference on GetSchema see:
    ' http://msdn2.microsoft.com/en-us/library/ms254934(VS.80).aspx

    Dim restrictions(3) As String
    restrictions(2) = tblName
    Dim dbTbl As DataTable = dbConn.GetSchema("Tables", restrictions)

    If dbTbl.Rows.Count = 0 Then
        'Table does not exist
        DoesTableExist = False
    Else
        'Table exists
        DoesTableExist = True
    End If

    dbTbl.Dispose()
    dbConn.Close()
    dbConn.Dispose()
End Function


''' <summary>
''' Checks to see if a field exists in table or not.
''' </summary>
''' <param name="tblName">Table name to check in</param>
''' <param name="fldName">Field name to check</param>
''' <param name="cnnStr">Connection String to connect to</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function DoesFieldExist(ByVal tblName As String, _
                               ByVal fldName As String, _
                               ByVal cnnStr As String) As Boolean
    ' For Access Connection String,
    ' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
    ' accessFilePathAndName

    ' Open connection to the database
    Dim dbConn As New OleDbConnection(cnnStr)
    dbConn.Open()
    Dim dbTbl As New DataTable

    ' Get the table definition loaded in a table adapter
    Dim strSql As String = "Select TOP 1 * from " & tblName
    Dim dbAdapater As New OleDbDataAdapter(strSql, dbConn)
    dbAdapater.Fill(dbTbl)

    ' Get the index of the field name
    Dim i As Integer = dbTbl.Columns.IndexOf(fldName)

    If i = -1 Then
        'Field is missing
        DoesFieldExist = False
    Else
        'Field is there
        DoesFieldExist = True
    End If

    dbTbl.Dispose()
    dbConn.Close()
    dbConn.Dispose()
End Function

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
My area of expertise is developing management database systems for business so that they can efficiently store and lookup existing customer's information and related data, and be able to generate various reports. My goal is to always deliver innovative design and a user friendly interface.

Comments and Discussions

 
QuestionThanks Pin
Member 1095537229-Aug-14 5:05
Member 1095537229-Aug-14 5:05 
QuestionExcellent! Pin
szmilo31-Jul-14 5:40
szmilo31-Jul-14 5:40 
GeneralVery Useful Pin
Kizza00724-Mar-14 0:36
Kizza00724-Mar-14 0:36 
GeneralRe: Very Useful Pin
Razi Syed28-Mar-14 8:23
Razi Syed28-Mar-14 8:23 
Questioncheck if table exists in particular database Pin
Ahmad Al Halabi29-Sep-13 12:42
Ahmad Al Halabi29-Sep-13 12:42 
QuestionGood ,, but what if table exists with ZERO Record. Pin
Rakesh_Sharma237-Jan-13 20:33
Rakesh_Sharma237-Jan-13 20:33 
QuestionGreat snippet Pin
nimblebits2-Jan-13 4:53
nimblebits2-Jan-13 4:53 
GeneralMy vote of 5 Pin
Renato Rolando9-Dec-10 4:02
Renato Rolando9-Dec-10 4:02 
GeneralExcellent , thanks for sharing Pin
hichem1474-Dec-10 1:29
hichem1474-Dec-10 1:29 
Generalgood article Pin
Donsw7-Feb-09 13:38
Donsw7-Feb-09 13:38 
GeneralNice and simple Pin
Petter Ivarsson24-Nov-08 8:49
Petter Ivarsson24-Nov-08 8:49 
GeneralRe: Nice and simple Pin
Razi Syed2-Dec-08 18:57
Razi Syed2-Dec-08 18:57 
QuestionDoes the getSchema need the user to have DBA permissions? Pin
anushyam17-Nov-08 6:36
anushyam17-Nov-08 6:36 
If so, then you can just query sysobjects,which will give you the same permission. I liked the second method though, since it does not call for any special permissions.

Nice articleSmile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.