我有一个关于在Access VBA中运行SQL的问题。我想基本上在vba中创建一个查询,但不要在我的数据库中创建一个查询。它只是坐在那里,看不见,直到使用它的操作完成,然后它就会消失。
我的代码如下(简化为专注于此问题)。我不认为我这样做是正确的,因为我认为在第二次查询时我需要做" & ECStart2SQL & "
这件事,但我不知道它是如何工作的,当我需要时引用一个值。
Private Sub TimeReportingButton_Click()
'THIS IS THE 1ST QUERY
Dim ECStart2SQL As String
ECStart2SQL = "SELECT D1.[#], (SELECT Count(*) FROM tbl_Data D2 WHERE D2.[#] = D1.[#] AND D2.[tsUpdated] <= D1.[tsUpdated]) AS Sequence, D1.tsUpdated FROM tbl_Data AS D1 WHERE ((((SELECT Count(*) FROM tbl_Data D2 WHERE D2.[#] = D1.[#] AND D2.[tsUpdated] <= D1.[tsUpdated]))=1)) ORDER BY D1.[#]"
'THIS IS THE 2ND QUERY, THE UPDATE QUERY, THAT REFERS TO THE FIRST ONE
Dim UpdECStartRank2SQL As String
UpdECStartRank2SQL = "UPDATE tbl_TimeReporting INNER JOIN ECStart2SQL ON tbl_TimeReporting.[#] = ECStart2SQL.[#] SET tbl_TimeReporting.ECStart = [ECStart2SQL]![tsUpdated] WHERE (((tbl_TimeReporting.ECStart) Is Null) AND ((tbl_TimeReporting.Sequence)=2))"
'OPERATION
DoCmd.SetWarnings False
DoCmd.RunSQL UpdECStartRank2SQL
MsgBox "Done!", , "Done!"
DoCmd.SetWarnings True
End Sub
如果您能提供任何帮助,请随时与我们联系。谢谢!
答案 0 :(得分:3)
要创建查询,请使用CreateQueryDef命令
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("MyQuery", "SELECT * FROM Table1")
现在,您可以像往常一样在SQL命令中使用查询,例如
"UPDATE MyTable INNER JOIN MyQuery ON ..."
要删除它,请使用QueryDefs.Delete
CurrentDb.QueryDefs.Delete "MyQuery"