我正在尝试使用INSERT INTO语句而不定义我的列字段名称。我知道这是可能的,但我不能做到这一点。我目前拥有的SQL字符串是,
strSQL = " INSERT INTO MLE_Table (pnr, [Overall Assesment], risk, reason, justification)" & _
" SELECT tbl_Import.pnr, tbl_Import.[Overall Assesment], tbl_Import.risk, tbl_Import.reason, tbl_Import.justification " & _
" FROM tbl_Import;"
现在,在这段代码中,我使用了我的字段名称。但我不想这样做。 我希望SQL只在两个表的字段名称匹配时才将字段插入到新表中。
我认为可以通过For Each Loop完成,但我不确定。
之前有没有人这样做过..我正在使用MS Access 2010。
非常感谢!!
答案 0 :(得分:0)
您可以使用DAO:
Public Sub CopyRecords()
Dim rstSource As DAO.Recordset
Dim rstInsert As DAO.Recordset
Dim fld As DAO.Field
Dim strSQL As String
Dim lngLoop As Long
Dim lngCount As Long
strSQL = "SELECT Top 1 * FROM tblInsert"
Set rstInsert = CurrentDb.OpenRecordset(strSQL)
strSQL = "SELECT * FROM tblSource"
Set rstSource = CurrentDb.OpenRecordset(strSQL)
With rstSource
lngCount = .RecordCount
For lngLoop = 1 To lngCount
With rstInsert
.AddNew
For Each fld In rstSource.Fields
With fld
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
ElseIf .Name = "Something" Then
' Insert default value.
rstInsert.Fields(.Name).Value = 0
ElseIf .Name = "SomethingElse Then
' Ignore this field.
Else
' Copy field content.
rstInsert.Fields(.Name).Value = .Value
End If
End With
Next
.Update
End With
.MoveNext
Next
rstInsert.Close
.Close
End With
Set rstInsert = Nothing
Set rstSource = Nothing
End Sub