[英]ADODB/Access: Update Multiple Fields from Record in Same Table
I'm using ADODB in Excel to query an Access database. 我在Excel中使用ADODB来查询Access数据库。 I'd like to use a row in a table as a template for another row (that already exists) in the same table.
我想在表中使用一行作为同一个表中另一行(已存在)的模板。 I've tried several UPDATE queries, some without syntax errors, but I can't ever get the update to go through.
我已经尝试了几个UPDATE查询,有些没有语法错误,但我无法让更新通过。
Assume the following table, Table1: 假设下表,表1:
+--------------------------------------------+
| ID | Field 1 | Field 2 | Field 3 | Field 4 |
| 1 | A | 1 | 9 | Z |
| 2 | B | 2 | 8 | Y |
| 3 | C | 3 | 9 | X |
| 4 | D | 4 | 6 | W |
| 5 | E | 5 | 5 | V |
+--------------------------------------------+
I want to copy Field2, Field3, and Field4 from Row 2 to Row 5 so the table after the update will be: 我想将Field2,Field3和Field4从第2行复制到第5行,因此更新后的表将是:
+--------------------------------------------+
| ID | Field 1 | Field 2 | Field 3 | Field 4 |
| 1 | A | 1 | 9 | Z |
| 2 | B | 2 | 8 | Y |
| 3 | C | 3 | 9 | X |
| 4 | D | 4 | 6 | W |
| 5 | E | 2 | 8 | Y |
+--------------------------------------------+
I've tried these two queries without success. 我试过这两个查询没有成功。 They both run without error, but the row does not get updated.
它们都运行没有错误,但行没有更新。
UPDATE Table1 A, Table1 B SET A.Field2=B.Field2, A.Field3=B.Field3, A.Field4=B.Field4
WHERE A.ID=B.ID AND A.ID=5 AND B.ID=2
UPDATE Table1 A INNER JOIN Table1 B ON A.ID=B.ID
SET A.Field2=B.Field2, A.Field3=B.Field3, A.Field4=B.Field4
WHERE A.ID=5 AND B.ID=2
Of course, I could SELECT the values that I want and then do an UPDATE, but I would think there would be an easy way to do this in one query. 当然,我可以选择我想要的值,然后进行更新,但我认为在一个查询中有一种简单的方法可以做到这一点。
UPDATE: The problem was that I was using an ADODB command for multiple queries and I forgot to set it to a NEW ADODB.Command before doing this Update. 更新:问题是我使用ADODB命令进行多次查询,我忘了在执行此更新之前将其设置为新的ADODB.Command。 I noticed this when I put the values in directly and specified Prepared=False and it worked.
当我直接输入值并指定Prepared = False并且它有效时,我注意到了这一点。 Below is the working code:
以下是工作代码:
Dim NewCommand As New ADODB.Command
Set NewCommand = New ADODB.Command
With NewCommand
Set .ActiveConnection = ExistingConnection
.CommandText = "UPDATE Table1 A, Table1 B SET A.Field2=B.Field2, " _
& "A.Field3=B.Field3, A.Field4=B.Field4 " _
& "WHERE A.ID=B.ID AND A.ID=? AND B.ID=?"
.Prepared = True: .CommandType = adCmdText
.Parameters.Append .CreateParameter("IDA", adInteger, adParamInput, 4, 2)
.Parameters.Append .CreateParameter("IDB", adInteger, adParamInput, 4, 5)
.Execute
End With
Here is one way to do it: 这是一种方法:
UPDATE Table1, Table1 AS Table1_2 SET Table1_2.Field2 = [Table1]![Field2],
Table1_2.Field3= [Table1]![Field3], Table1_2.Field4= [Table1]![Field4]
WHERE (((Table1.ID)=2) AND ((Table1_2.ID)=5));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.