在MS Access中,我有一个未绑定的表单,其中包含两个格式为“短日期”的字段,因此我可以显示日期选择器(Access 2007)。 单击按钮,数据将在vba
中使用此sql查询插入表中strInsert = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type, fday, reqday) " & _
"VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "','" & Me.cboType & "','" & Me.fday & "','" & Me.reqday & "')"
表格中的fday和reqday是时间/日期字段,并设置为“required = No”。
如果填写了表单上的两个日期字段,一切顺利,但如果其中任何一个都为空,我会得到“由于类型转换失败而将1个字段设置为Nul”错误,因为它试图放置一个空字符串到日期/时间字段。
有没有人知道我可以将这些字段留空并且仍然可以使用插入查询工作?
感谢您的帮助。 如果有人想知道,这就是我最终做到的方式。
Dim strInsert0 As String
Dim strInsert1 As String
Dim strInsert2 As String
Dim strInsert3 As String
Dim strCid As String
strCid = Forms!frmCustomer!cid
strInsert0 = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type) " & _
"VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "'," & _
"'" & Me.cboType & "')"
strInsert1 = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type, fday) " & _
"VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "'," & _
"'" & Me.cboType & "','" & Me.fday & "')"
strInsert2 = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type, reqday) " & _
"VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "'," & _
"'" & Me.cboType & "','" & Me.reqday & "')"
strInsert3 = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type, fday, reqday) " & _
"VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "'," & _
"'" & Me.cboType & "','" & Me.fday & "','" & Me.reqday & "')"
If IsNull(Me.reqday) And Not IsNull(Me.fday) Then
DoCmd.RunSQL strInsert1
ElseIf IsNull(Me.fday) And Not IsNull(Me.reqday) Then
DoCmd.RunSQL strInsert2
ElseIf IsNull(Me.reqday) And IsNull(Me.fday) Then
DoCmd.RunSQL strInsert0
Else: DoCmd.RunSQL strInsert3
End If
拥有两个日期字段,其中任何一个都可能是空的,但稍微复杂一点。
答案 0 :(得分:1)
我不确定,但我相信你不能存储空值。如果我是你,我会运行一个if语句来检查它们是否为空。请查看以下代码:
if len(me.fday.value) > 0 and len(me.reqday.value) > 0 then
strInsert = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type, fday, reqday) " & _ "VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "','" & Me.cboType & "','" & Me.fday & "','" & Me.reqday & "')"
else
strInsert = "INSERT INTO atbl_invoice (cust_id, inv_date, job_no, item_desc, job_desc, type) " & _ "VALUES(" & strCid & ", Date(),'" & Me.JobNo & "','" & Me.item_desc & "','" & Me.job_desc & "','" & Me.cboType & "')"
end if
看看是否有效,如果没有,请回答评论并告诉我。
答案 1 :(得分:-2)
在sql字符串中,使用以下查询:
插入mytable(mydata)值(#01/01/2020#)
或
插入mytable(mydata)值(NULL)