我有一個使用OTA API查詢HP ALM數據庫的VBA腳本。如何在VBA腳本中編寫CTE遞歸查詢?
我想使用遞歸CTE查詢數據庫。我不知道如何在該VBA腳本中編寫該腳本。
VBA腳本:::
Sub Extractor()
Const QCADDRESS = "http://alm/qcbin"
Const DOMAIN = "DOMAIN"
Const PROJECT = "PROJECT"
Const QCUSR = "user.name"
Const QCPWD = "123456"
Dim QCConnection, com, recset
Dim XLS, Wkb, Wks, i
Set QCConnection = CreateObject("TDApiOle80.TDConnection")
QCConnection.InitConnectionEx QCADDRESS
QCConnection.Login QCUSR, QCPWD
QCConnection.Connect DOMAIN, PROJECT
Set com = QCConnection.Command
com.CommandText = "Select * from ALL_LISTS"
Set recset = com.Execute
Set XLS = CreateObject("Excel.Application")
XLS.Visible = False
Set Wkb = XLS.Workbooks.Add
Set Wks = Wkb.Worksheets(1)
i = 1
Wks.Cells(i, 1).Value = "Data"
If recset.RecordCount > 0 Then
i = 2
recset.First
Do While Not (recset.EOR)
Wks.Cells(i, 1).Value = recset.FieldValue(0) 'fieldvalue(0) because the query extract only 1 field.
i = i + 1
recset.Next
Loop
Wkb.SaveAs "C:\myfile.xls"
End If
Wkb.Close
XLS.Quit
QCConnection.Disconnect
Set recset = Nothing
Set com = Nothing
Set QCConnection = Nothing
Set XLS = Nothing
Set Wkb = Nothing
Set Wks = Nothing
End Sub
CTE查詢::::
with ReqCTE
as
(
SELECT
RQ_REQ_ID,
RQ_REQ_NAME,
RQ_FATHER_ID,
0 as lvl
FROM
td.REQ
where
RQ_REQ_ID = {?Father_ID}
union all
select
Folders.RQ_REQ_ID,
Folders.RQ_REQ_NAME,
Folders.RQ_FATHER_ID,
Child.lvl +1
from
ReqCTE as Child
join td.REQ as Folders on Folders.RQ_REQ_ID = Child.RQ_FATHER_ID
);
select * from ReqCTE;
VBA中的scipt與SQL-Server中的相同。只需將SQL-Statemen放入一個字符串變量並打開一個記錄集 – CPMunich
它可以用於多個語句查詢嗎? –
是的。讀完所有行後,您需要使用['NextRecordset'](https://msdn.microsoft.com/en-us/library/ms677539%28v=vs.85%29.aspx)語句來開始下一行的行。 – Richard