Geeks With Blogs
Razi Syed Professional Developer

Here is a function I wrote to check and see if a field exists in a table or not:

    ''' <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

Posted on Thursday, November 13, 2008 11:21 AM Visual Basic 2005 , SQL Server 2005 | Back to top


Comments on this post: Function to check if a Field exists in a database Table or not

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © razisyed | Powered by: GeeksWithBlogs.net