2017-06-05 117 views
0

我收到了一个INSERT INTO错误,我似乎无法弄清楚。代码遍历一个Dao记录集,以便只将某些记录附加到表中。访问VBA INSERT INTO时遇到问题

Dim maxDate As Variant 

Dim db As DAO.Database 
Dim rs As DAO.Recordset 
Dim sqlinsert As String 

maxDate = DMax("[Eff Date]", "400_CF_BREAK_LOG") 
Set db = CurrentDb 


Set rs = db.OpenRecordset("860_APPEND_DIFFERENCES") 
If Not rs.BOF Then 
    'populate the table 
    rs.MoveFirst 
    Do 
     If (rs![Eff Date] > maxDate Or IsNull(maxDate)) Then 
      sqlinsert = "INSERT INTO 400_CF_BREAK_LOG (Eff Date, PrimarySecurity ID Number, CUSIP(Aladdin ID), IsrName, Asset Type, Metlife Port Code, Business Unit, Principal Difference, Total PAM Principal, Total Aladdin Principal,Income Difference, Total PAM Interest,Total Aladdin Interest,Total CF Difference,Total PAM CF,PAM Coupon)" & _ 
      " VALUES ('" & rs("Eff Date") & "', '" & rs("PrimarySecurity ID Number") & "', '" & rs("CUSIP(Aladdin ID)") & "', '" & rs("IsrName") & "', '" & rs("Asset Type") & "', '" & rs("Metlife Port Code") & "', '" & rs("Business Unit") & "', '" & rs("Principal Difference") & "', '" & rs("Total PAM Principal") & "', '" & rs("Total Aladdin Principal") & "','" & rs("Income Difference") & "', '" & rs("Total PAM Interest") & "', '" & rs("Total Aladdin Interest") & "', '" & rs("Total CF Difference") & "', '" & rs("Total PAM CF") & "', '" & rs("PAM Coupon") & "') " 
      DoCmd.RunSQL (sqlinsert) 
     End If 
     rs.MoveNext 
    Loop Until rs.EOF 
End If 

我不断收到INSERT INTO语句中的语法错误,但我已经检查了几次。

编辑 - 说明。标签

+3

你不能使用空格,你需要使用'[生效日期]' –

+1

作为@Nathan_Sav说,只是有很多在您的查询比'[生效日期]多个名称用空格'独自一人,他们都需要用方括号括起来。另外,介意变量类型。如果[Eff Date]是日期而不是字符串,那么您正在处理它不正确。另外请注意,如果您上面共享的代码已完成,则可以用单个附加查询替换它,并且运行得更有效并且更易于调试。 –

+0

@ErikvonAsmuth不幸的是,我不能运行追加查询,因为它添加了一批记录,而我需要检查每条记录然后添加它。 – FamousFrik

回答

1

带空格或标点符号/特殊字符的名称(只有例外是下划线)需要包含在[]中。最好避免这些命名约定。但是,对带有引号的记录集字段的引用不应该在[]中进行封闭。另一种需要[]的语法是:rs![Eff Date]

sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Eff Date], [PrimarySecurity ID Number], 
[CUSIP(Aladdin ID)], IsrName, [Asset Type], [Metlife Port Code], [Business Unit], 
[Principal Difference], [Total PAM Principal], [Total Aladdin Principal], 
[Income Difference], [Total PAM Interest], [Total Aladdin Interest], [Total CF Difference], 
[Total PAM CF], [PAM Coupon])" & _ 
" VALUES ('" & rs("Eff Date") & "', '" & rs("PrimarySecurity ID Number") & "', '" & 
rs("CUSIP(Aladdin ID)") & "', '" & rs("IsrName") & "', '" & rs("Asset Type") & "', '" & 
rs("Metlife Port Code") & "', '" & rs("Business Unit") & "', '" & rs("Principal Difference") & "', '" & 
rs("Total PAM Principal") & "', '" & rs("Total Aladdin Principal") & "','" & 
rs("Income Difference") & "', '" & rs("Total PAM Interest") & "', '" & 
rs("Total Aladdin Interest") & "', '" & rs("Total CF Difference") & "', '" & rs("Total PAM CF") & "', '" & 
rs("PAM Coupon") & "') " 
+0

谢谢。不幸的是,我使用的不是我自己设计的遗留系统 – FamousFrik

+0

另外,我只注意到使用撇号分隔符来表示日期/时间和数字字段。撇号应该只用于文本字段。 #用于日期/时间,号码类型不需要分隔符。是文本类型的所有字段? – June7

+0

不,你能举个例子吗? Eff数据是日期。 – FamousFrik