简体   繁体   English

SQL VBA:选择具有特定表名和字段名的所有表

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

im working with access and VBA. 我正在使用访问和VBA。 As for now, I am trying to create a query with a SQL statement. 就目前而言,我正在尝试使用SQL语句创建查询。 I have a bunch of tables, all of them are named "innen" at the end and they vary at the start. 我有一堆桌子,它们都在末尾被命名为“ innen”,并且它们在开始时有所不同。 Each of these tables contain the column name "OP" (also other field names). 这些表中的每一个都包含列名“ OP”(还有其他字段名)。 Now my goal is to select all tables with the name containing '%innen' and the column name "OP". 现在,我的目标是选择名称包含“%innen”和列名称“ 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? 它甚至可以通过vba与sql语句一起使用?

Here is a VBA solution for you. 这是为您提供的VBA解决方案。

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. 我敢打赌,有一种方法可以使相同的事情只使用SQL。 Although, Access is a unique animal. 虽然,Access是一种独特的动物。 You can do this using SQL Server. 您可以使用SQL Server执行此操作。 I'm not 100% sure Access can handle it. 我不确定100%Access是否可以处理它。 Well, why not try it and see for yourself. 好吧,为什么不试试看自己呢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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