查询问题

时间:2009-07-13 15:51:05

标签: sql ms-access vba access-vba

执行此查询时:

Dim Var
Var = ("select max(Autonumber) from tblAutonumber")
DoCmd.RunSQL (Var)

我将var的值设为"select max(Autonumber) from tblAutonumber",而不是我要查找的最大值。

代码:

Private Sub btnSubmit_Enter()
DoCmd.RunSQL ("insert into tblAutonumber (Dummy)values ('DummyValue')")

Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strMaxNum As String
Dim strSQL As String

strSQL = "select max(Autonumber) as maxNum from tblAutonumber"
Set db = CurrentDb
Set rst = db.OpenRecordset(strSQL)

 rst.MoveFirst
 strMaxNum = rst!maxNum
'Dim Var As Variant
'Var = "select max(Autonumber) from tblAutonumber"
'DoCmd.RunSQL (Var)
txtAutoNumber.Value = strSQL
DoCmd.RunSQL ("insert into tbltesting (Empid,TestScenario,owner,event,version,expresult,variation,status,homestore)values ('" & Me.txtEmpNo.Value & "','" & Me.txtTestScenario.Value & "','" & Me.txtOwner.Value & "','" & Me.txtEvent.Value & "', '" & Me.txtVersion.Value & "','" & Me.txtExpectedResult.Value & "', '" & Me.txtVariation.Value & "', '" & Me.txtStatus.Value & "','" & Me.txtHomeStore.Value & "')")
'DoCmd.RunSQL ("INSERT INTO tblContract(testid)select max(testid) FROM tbltesting")
 DoCmd.RunSQL ("insert into tblContract (Empid,testid,Start1,Finish1,Store1,Start2,Finish2,Store2 )values ('" & Me.txtEmpNo.Value & "','" & Me.txtAutoNumber.Value & "','" & Me.txtContSunStart1.Value & "', '" & Me.txtContSunFinish1.Value & "','" & Me.txtContSunStore1.Value & "','" & Me.txtContSunStart2.Value & "', '" & Me.txtContSunFinish2.Value & "','" & Me.txtContSunStore2.Value & "')")
 'DoCmd.RunSQL = "INSERT INTO tblContract (Empid,testid, Start1, Finish1, Store1, Start2, Finish2, Store2)  SELECT " & Me.txtEmpNo.Value & "', MAX(testid), '" & Me.txtContSunStart1.Value & "', '" & Me.txtContSunFinish1.Value & "','" & Me.txtContSunStore1.Value & "','" & Me.txtContSunStart2.Value & "', '" & Me.txtContSunFinish2.Value & "','" & Me.txtContSunStore2.Value & "' " & "FROM tbltesting'"
'DoCmd.RunSQL = "INSERT INTO tblContract (Empid,testid, Start1, Finish1, Store1, Start2, Finish2, Store2)  SELECT " & Me.txtEmpNo.Value & "', MAX(testid), '" & Me.txtContSunStart1.Value & "', '" & Me.txtContSunFinish1.Value & "','" & Me.txtContSunStore1.Value & "','" & Me.txtContSunStart2.Value & "', '" & Me.txtContSunFinish2.Value & "','" & Me.txtContSunStore2.Value & "' " & "FROM tbltesting'"
End Sub

3 个答案:

答案 0 :(得分:1)

对于您要完成的任务,您可能只想使用DMAX域聚合函数,该函数将返回给定域(即表)的最大表达式(即列)。这是一个例子:

  Dim lastAutonumber As Long
  lastAutonumber = DMax("Autonumber", "tblAutonumber")

答案 1 :(得分:0)

正如Rich所评论的那样:

Dim Var 
Var = "select max(Autonumber) from tblAutonumber"
DoCmd.RunSQL (Var)

答案 2 :(得分:0)

使用Access UI:

Dim Var As Long
var = CurrentProject.Connection.Execute("select max(Autonumber) from tblAutonumber;")(0)