sql
  • excel
  • vba
  • ado
  • 2014-07-03 119 views 1 likes 
    1

    我有一個帶有各種文本框的excel用戶表單,有些用於輸入日期的字段。用戶然後可以保存他們的條目。將VBA中的Empty/Null Date變量傳遞給SQL UPDATE語句

    此時,我通過ADO連接連接到訪問後端。由用戶輸入的值傳遞給SQL字符串,例如,

    strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _ 
         "tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _ 
         "tblDECONVERSION_DATA.DateRecieved = #" & Format(NewBusiness_WorkQueue.Decon_DateRecieved, "mm/dd/yyyy") & "#, " & _ 
         "tblDECONVERSION_DATA.WireDate = #" & Format(NewBusiness_WorkQueue.Decon_WireDate, "mm/dd/yyyy") & "#, " & _ 
         "tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & "', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _ 
         "WHERE (((tblDECONVERSION_DATA.CaseID)=" & ID & "));" 
    
         adoRecSet.Open Source:=strSQL, ActiveConnection:=dbconnect, CursorType:=adOpenDynamic, LockType:=adLockOptimistic 
    

    然而,一些日期字段可留空,這意味着例如NewBusiness_WorkQueue.Decon_DateRecieved變量是空的。這會導致語法錯誤。如何在VBA和Access數據庫都可以接受的SQL語句中傳遞Null或Empty日期變量?

    +1

    如果日期是空白,那麼你需要設置字段爲「空」,但你不能這樣做,包裹在''#。我會創建一個函數(例如「DateOrNull」)來檢查日期輸入並返回適當的SQL。 –

    +0

    您是否有遇到過日期並將其更新爲NULL的情況?如果沒有,你可以不更新該字段。 –

    +0

    @TimWilliams感謝您的建議。我的實際SQL語句非常長,最多可以包含10個日期變量。有沒有辦法讓一個大的SQL字符串,如果日期字段爲空或空,則傳遞null。或者如果用戶輸入了一個包含日期的變量?例如。如果IsDate(LastLogInTime)then sqlVar =「#」&LastLogInTime&「#」否則sqlVar =「Null」。然後將sqlVar傳遞給SQL字符串? strSQL =「UPDATE tblTestDates SET tblTestDates.TestDate2 =」&sqlVar&「」&_ 「(((tblTestDates.CaseID)=」&ID & "));「 – mccreaVBA

    回答

    2
    strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & _ 
          NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _ 
         "tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _ 
         "tblDECONVERSION_DATA.DateRecieved = " & _ 
          DateOrNull(NewBusiness_WorkQueue.Decon_DateRecieved) & ", " & _ 
         "tblDECONVERSION_DATA.WireDate = " & _ 
          DateOrNull(NewBusiness_WorkQueue.Decon_WireDate) & ", " & _ 
         "tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & _ 
         "', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _ 
         "WHERE tblDECONVERSION_DATA.CaseID=" & ID & ";" 
    

    一個例子功能:

    Function DateOrNull(v) As String 
        Dim rv as String 
        If IsDate(v) Then 
         rv = " #" & Format(v, "mm/dd/yyyy") & "# " 
        Else 
         rv = " null " 
        End If 
        DateOrNull = rv 
    End Function 
    
    相關問題