在Ms Access SQL中设置最大ID标准

时间:2017-08-21 15:13:46

标签: sql ms-access dao

此查询不会在开头运行。有人可以帮忙看看有什么问题吗? 如果有任何其他方式可以实现这种建议。

strSQL1 = "SELECT * FROM PharmSales WHERE HospitalNo='" & Me.txtRegNo & 
          "' And TDate = #" & Format(Me.txtTDate, "M\/dd\/yyyy") & 
          "# AND SalesItem1 = '" & Me.txtSalesItem1 & "' And
          PharmSalesID=
               (SELECT MAX(PharmSalesID) FROM PharmSales)"

    Set pr = db.OpenRecordset(strSQL1)

    With pr
    If Not .BOF And Not .EOF Then  'Ensure that the recordset contains records
    .MoveLast
    .MoveFirst
     If .Updatable Then  'To ensure record is not locked by another user
     .Edit  'Must start an update with the edit statement
     If IsNull(![TotalPaid]) = True And Me.txtGrand_TotalPay.Value >= Me.txtSalesAmt1.Value Then
     ![DispQty1] = Nz(![DispQty1] + Me.txtSalesQty1.Value, 0)
      .Update
           ElseIf IsNull(![TotalPaid]) = False And (Me.txtGrand_TotalPay.Value - Me.txtSalesAmt1.Value) >= (txtGrand_TotalFee - Me.txtGrand_TotalPay.Value + Me.txtSalesAmt1.Value) Then
     ![DispQty1] = Nz(![DispQty1] + Me.txtSalesQty1.Value, 0)
      .Update

     Else: MsgBox ("Insufficient balance!")
     End If
    End If
    End If

     pr.Close 
     Set pr = Nothing 
    Set db = Nothing
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

您的SQL检查多个条件,但您的子查询没有任何这些条件,因此它可能会选择一个不符合您的其他条件的记录,从而导致您的记录集始终为空。

您需要将这些条件添加到子查询,而不是主查询。 由于子查询只返回一条记录,因此您无需将它们添加到两条记录中。

strSQL1 = "SELECT * FROM PharmSales" & _ 
          " WHERE PharmSalesID=" & _ 
               " (SELECT MAX(PharmSalesID) FROM PharmSales" & _ 
               " WHERE HospitalNo='" & Me.txtRegNo & _
               "' And TDate = #" & Format(Me.txtTDate, "M\/dd\/yyyy") & _
               "# AND SalesItem1 = '" & Me.txtSalesItem1 & "')"