2015-09-22 68 views
-2

我想借助VBA查找Select查询中涉及的表名。例如,我必须在slottime和time中找出涉及以下查询的表格。解析SELECT查询

SELECT MAX(theCount) FROM 
    (SELECT FK_Hour, Count(FK_Hour) As theCount FROM 
     (Select FK_Hour 
     From slottime 
     INNER JOIN time ON slottime.FK_Hour = time.Hour 
     WHERE FK_Hour in 
      (SELECT time.Hour FROM time WHERE time.day=0) 
     ) As C 
     GROUP By FK_Hour 
    ) AS counts; 

VBA有可能吗?

回答

0

希望这有助于:

Dim intFrom As Integer 
Dim strSql As String 
Dim colTables As New Collection 

strSql = "SELECT MAX(theCount) FROM (SELECT FK_Hour, Count(FK_Hour) As theCount FROM (Select FK_Hour From slottime INNER JOIN time ON slottime.FK_Hour = time.Hour WHERE FK_Hour in (SELECT time.Hour FROM time WHERE time.day=0)) As C GROUP By FK_Hour) AS counts" 
intFrom = 1 

Do While intFrom > 0 
    intFrom = InStr(intFrom, strSql, "FROM", vbTextCompare) 
    If InStr(intFrom + 5, strSql, "(", vbTextCompare) = 0 Then 'not the bracket 
     Call colTables.Add(Mid(strSql, intFrom + 5, InStr(intFrom + 6, strSql, " ", vbTextCompare) - intFrom - 5)) 
    End If 

    If intFrom = 0 Then Exit Do 

    intFrom = intFrom + 1 
Loop 

你应该做你的 “加入” 相同。

最好的问候,沃特

+0

其实我要寻找一个更通用的代码来解析任何SQL查询。该解决方案在许多情况下不起作用。 – user3471254

0
Public Sub TableNames() 
Dim SQuerry As String ' text to parse 
Dim FStart As Long ' place to start (or resume) the analysis of the text being parsed 
Dim TName As String ' current possible table name 
Dim TAllNames As String ' All table names to parse 

SQuerry = "SELECT MAX(theCount) FROM (SELECT FK_Hour, Count(FK_Hour) As theCount FROM (Select FK_Hour From slottime INNER JOIN time ON slottime.FK_Hour = time.Hour WHERE FK_Hour in (SELECT time.Hour FROM time WHERE time.day=0)) As C GROUP By FK_Hour) AS counts;" 
FStart = 1 
TAllNames = "," 
Do Until found1 = "0" 'found1 + 6 > InStrRev(squerry, " ", -1, 1) Or 
    found1 = InStr(FStart, SQuerry, "From", 1) 
    If Mid(SQuerry, found1 + 5, 1) = "(" Then 
     FStart = found1 + 1 
    Else 
     TName = Mid(SQuerry, found1 + 5, InStr(found1 + 5, SQuerry, " ", 1) - found1 - 5) 
     If InStr(1, TAllNames, "," & TName & ",", 1) = 0 And found1 > 0 Then TAllNames = TAllNames & TName + "," 
     FStart = found1 + 1 
    End If 
Loop 

'tallnames is a string of comma separated values starting and ending with a blank value (comma) 
Debug.Print TAllNames 
MsgBox  TAllNames