我使用Access VBA连接到SQL Server并从指定的数据库打印出表信息。我可以连接,我可以打印出表信息没问题。当我添加一个IF
语句时,我的代码只是去往并且永远不会打印出所需的结果。例如,我的Debug.Print
语句将返回
Test_1
Test_2
Red
Blue
但是,如果我取消注释if语句并尝试执行语法,则不会抛出任何错误,访问只会冻结我。我希望的结果是打印Like Test*
的两个表名称。为了打印这些数据,我的语法应该如何改变?
Public Sub GetTableNames()
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Dim f As ADODB.Field
Set c = New ADODB.Connection
With c
.Provider = "sqloledb.1"
With .Properties
.Item("Data Source") = "server"
.Item("Initial Catalog") = "database"
.Item("PassWord") = "password"
.Item("User ID") = "userid"
End With
.Open
Set r = .OpenSchema(adSchemaTables,Array(Empty, Empty, Empty, "TABLE"))
With r
While Not .EOF
'IF (.Fields("Table_Name") LIKE "Test*") THEN
Debug.Print .Fields("TABLE_NAME"), .Fields("TABLE_TYPE")
.MoveNext
'END IF
Wend
End With
End With
End Sub
答案 0 :(得分:0)
你很亲密。您的问题不在于IF
语句,而在于.MoveNext
的定位因为该语句在IF
块内,所以您永远不会迭代到下一个表,所以每个都通过你只看第一张桌子。话虽如此,我认为Blue
是你的第一个表名。
将您的代码更改为此代码,您将全部设置。
Public Sub GetTableNames()
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Dim f As ADODB.Field
Set c = New ADODB.Connection
With c
.Provider = "sqloledb.1"
With .Properties
.Item("Data Source") = "server"
.Item("Initial Catalog") = "database"
.Item("PassWord") = "password"
.Item("User ID") = "userid"
End With
.Open
Set r = .OpenSchema(adSchemaTables,Array(Empty, Empty, Empty, "TABLE"))
With r
While Not .EOF
IF (.Fields("Table_Name") LIKE "Test*") THEN
Debug.Print .Fields("TABLE_NAME"), .Fields("TABLE_TYPE")
END IF
.MoveNext
Wend
End With
End With
End Sub