简体   繁体   中英

SQL VBA: Selecting all tables with specific table name and field name

im working with access and VBA. As for now, I am trying to create a query with a SQL statement. I have a bunch of tables, all of them are named "innen" at the end and they vary at the start. Each of these tables contain the column name "OP" (also other field names). Now my goal is to select all tables with the name containing '%innen' and the column name "OP". So far i tried this:

Sub Aktuell()
Dim strSQL As String
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As QueryDef

    strSQL = "SELECT [*].OP FROM MSysObjects WHERE TABLE_NAME LIKE '%innen' ORDER BY MAX;"
    db.Execute strSQL

    Set qdf = CurrentDb.CreateQueryDef("NewQuery8", strSQL)
    DoCmd.OpenQuery qdf.Name

End Sub

i tried this here aswell:

strSQL = "SELECT * " & _
    "FROM INFORMATION_SCHEMA.TABLES " & _
    "WHERE COLUMN_NAME = 'OP_Datum';"

But i keep getting errors.

Any ideas? does it even work with a sql statement via vba?

Here is a VBA solution for you.

Option Compare Database

Function GetFieldList(TableName As String) As String()
  On Error GoTo Er
  Dim Flds() As String
  Dim fc As Long
  Dim I As Long

  'Initialize Dynamic Flds() Array
  Flds = Split("")
  fc = CurrentDb.TableDefs(TableName).Fields.Count - 1
  If fc >= 0 Then
    ReDim Preserve Flds(fc)
    For I = 0 To fc
      Flds(I) = CurrentDb.TableDefs(TableName).Fields(I).Name
    Next I
  End If
Done:

  GetFieldList = Flds
  Erase Flds
  Exit Function
Er:
  Resume Done

End Function

Sub flTest()
  Dim I As Long
  Dim Fields As Variant

  Fields = GetFieldList("Customers")
  If UBound(Fields) = -1 Then
    MsgBox "Table Not Found, or Table has no fields", vbCritical + vbOKOnly
    Exit Sub
  End If

  For I = LBound(Fields) To UBound(Fields)
    Debug.Print """" & Fields(I) & """"
  Next I


End Sub

I'll bet there is a way to so the same thing using nothing but SQL. Although, Access is a unique animal. You can do this using SQL Server. I'm not 100% sure Access can handle it. Well, why not try it and see for yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM