VBA中的SQL String语法错误

时间:2016-02-11 13:44:39

标签: sql vba ms-access

我有这个SQL字符串

theSQL = "INSERT INTO tbl_PROJECTS (co_id, contact_id, prop_id, worktype_id, incharge_id, project_name, project_ref," _
    & "project_status, project_awardref, project_awarddate, project_startdate, project_targetdate," _
    & "project_completedate, project_finalreportdate, project_location, project_notes)"

theSQL = theSQL & " VALUES (" & theCoID & "," & theContactID & "," & thePropID & "," & theWorkTypeID & "," & theInCharge & "," _
      & "'" & theProjectName & "'" & "," & theProjectRef & "," & theProjectStatus & "," & theAwardRef _
      & theAwardDate & "," & theStartDate & "," & theTargetDate & "," & theCompleteDate & "," & theFinalReportDate & "," _
      & theLocation & "," & theNotes & ")"

当我DoCmd.RunSQL (theSQL)时,我收到语法错误(运行时错误3134)。

我将输出发送到Debug.Print。无法找到语法错​​误。

任何能告诉VBA这个sql命令有什么问题的人吗?

有些变量是空的,如thetargetdatethecompletedate,我在此查询中未包含projectID,因为它是自动编号。我想要自动生成数字。

是否不允许将空值传递给SQL?

由于

DEBUG PRINT RESULT:

 INSERT INTO tbl_PROJECTS (co_id, contact_id, prop_id, worktype_id,
 incharge_id, project_name, project_ref, project_status,
 project_awardref, project_awarddate, project_startdate,
 project_targetdate, project_completedate, project_finalreportdate,
 project_location, project_notes) VALUES (61,66,134,1,1,'STRUCTURAL
 DESIGN',,AWARDED,Test LPO,2/11/2016,,,,,Dnata 4 storey warehouse,)

2 个答案:

答案 0 :(得分:3)

  

是否不允许将空值传递给SQL?

是的,但不能通过陈述空间来完成。你必须写Null:

VALUES (61,66,134,1,1,'STRUCTURAL DESIGN',Null,'AWARDED','Test LPO',#2/11/2016#,Null,Null,Null,Null,'Dnata 4 storey warehouse Alquoz',Null)

并且缺少引号和日期分隔符。

答案 1 :(得分:0)

你写了这个:

theSQL = "INSERT INTO tbl_PROJECTS (co_id, contact_id, prop_id, worktype_id, incharge_id, project_name, project_ref," _
    & "project_status, project_awardref, project_awarddate, project_startdate, project_targetdate," _
    & "project_completedate, project_finalreportdate, project_location, project_notes)"

theSQL = theSQL & " VALUES (" & theCoID & "," & theContactID & "," & thePropID & "," & theWorkTypeID & "," & theInCharge & "," _
      & "'" & theProjectName & "'" & "," & theProjectRef & "," & theProjectStatus & "," & theAwardRef _
      & theAwardDate & "," & theStartDate & "," & theTargetDate & "," & theCompleteDate & "," & theFinalReportDate & "," _
      & theLocation & "," & theNotes & ")"

在第二个区块的第二行,没有结束引号。