我已将MS Access前端链接到SQL Server(并以某种方式后悔该决定)。现在我有一堆程序与复杂但相似的WHERE
部分但不同的SELECT DISTINCT
所以我想将它们组合成一个单独的程序,如
SELECT * FROM myTable1 INNER JOIN @tblFromFunc()
SELECT * FROM myTable2 INNER JOIN @tblFromFunc()
和一个预定义的表值函数@tblFromFunc
,它将只处理我的WHERE
一次。希望获得更好的性能并使维护更容易。
这在SQL Server上工作正常,我甚至可以通过在vba中使用DAO.QueryDef
和DAO.Recordset
获得MS Access中可见的两个独立结果中的第一个(只是尝试了其中两个)。
我发现.NextRecordset
here的这个描述,简称为vba:
DIM rst as DAO.Recordset
SET rst = functionConnectServer("NameOfSp")
booNext = True
intCount = 1
With rst
Do While booNext
Do While Not .EOF
Debug.Print , .Fields(0), .Fields(1)
.MoveNext
Loop
booNext = .NextRecordset
intCount = intCount + 1
Loop
End With
但如果我在Acceess 2010中使用它,我得到了回应,不知何故.NextRecordset
is不再受支持了。所以我不能移动到第二个记录集,说实话,我甚至不确定,如果第二个记录集到达我的前端。
任何提示都会让我感到高兴,我甚至对这个问题采取完全不同的策略。
虽然DAO方法要求特定对象使用复合SQL语句,但请考虑分配给NextRecordset的ADO连接:
' REFERENCE Microsoft ActiveX Data Objects 2.* Library
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
conn.Open "Driver={SQL Server};Server=server;Database=db;Trusted_connection=yes;"
rst.Open "EXEC myStoredProc", conn
' FIRST RECORDSET
With rst
Do While Not .EOF
Debug.Print , .Fields(0), .Fields(1)
.MoveNext
Loop
End With
' SECOND RECORDSET
Set rst = rst.NextRecordset()
With rst
Do While Not .EOF
Debug.Print , .Fields(0), .Fields(1)
.MoveNext
Loop
End With
rst.Close()
conn.Close()
Set rst = Nothing
Set conn = Nothing
虽然您可能无法循环遍历许多结果集,但您可以将循环放在已定义的函数中并在每个Set
之后调用它:
Function RetrieveData(rs As Recordset)
With rs
Do While Not .EOF
Debug.Print , .Fields(0), .Fields(1)
.MoveNext
Loop
End With
End Function
Sub DatabaseProcess()
...
rst.Open "EXEC myStoredProc", conn
' FIRST RECORDSET
Call RetrieveData(rst)
' SECOND RECORDSET
Set rst = rst.NextRecordset()
Call RetrieveData(rst)
rst.Close(): conn.Close()
Set rst = Nothing: Set conn = Nothing
End Sub