Is there a way to determine if a column exists in a table?

R

Ron

My code is building SQL based on user input. Is there a way I can test to see
if a specified column really exists in a table before executing SQL that
references it?
Thanks
 
J

John Nurick

Hi Ron,

How about something like this:


Public Function DoesFieldExist( _
TableName As String, _
FieldName As String) As Boolean

Dim SQL As String
Dim rsR As DAO.Recordset
Dim F As DAO.Field

SQL = "SELECT * FROM " & TableName & " WHERE FALSE;"
Set rsR = CurrentDb.OpenRecordset(SQL)
On Error Resume Next
Set F = rsR.Fields(FieldName)
If Err.Number = 0 Then
DoesFieldExist = True
Else
DoesFieldExist = False
End If
On Error GoTo 0
rsR.Close
End Function
 
M

Marshall Barton

Ron said:
My code is building SQL based on user input. Is there a way I can test to see
if a specified column really exists in a table before executing SQL that
references it?


Here's some logic that applies:

Set db = CurrentDb()
Set tdf = db.TableDefs!tablename
. . .
For Each fld In tdf
If fld.Name = strfieldname Then
bolFieldExists = True
End If
Next fld
If bolFieldExists Then
'all is good
. . .
Else
'bad field name
. . .
End If
. . .
Set tdf = Nothing
Set db = Nothing
 
R

Ron

Thanks for your help!
Regards,
Ron

Marshall Barton said:
Here's some logic that applies:

Set db = CurrentDb()
Set tdf = db.TableDefs!tablename
. . .
For Each fld In tdf
If fld.Name = strfieldname Then
bolFieldExists = True
End If
Next fld
If bolFieldExists Then
'all is good
. . .
Else
'bad field name
. . .
End If
. . .
Set tdf = Nothing
Set db = Nothing
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top