如何返回更新行的详细信息?

时间:2020-03-19 13:25:28

标签: excel vba ms-access ms-access-2016

我在MS Access 2016中具有数据库,并且想通过Excel VBA运行更新查询-这可行。之后,我想返回更新的行的详细信息(来自两列的值-ID,Col1)。现在,我只有一些受影响的行。如何做到这一点?

我的查询:

UPDATE 
(SELECT TOP 1 ID, Col1, Update_time, Update_user 
FROM Table1 
WHERE Update_user Is Null 
ORDER BY Col2 DESC , ID)  AS U_ROW 
SET U_ROW.Update_time = Now(), U_ROW.Update_user = [username];

在Excel VBA中,我通过ADODB运行它。命令:

    With baseRecordsetCommand
        .ActiveConnection = objectConnection
        .CommandType = adCmdStoredProc
        .CommandText = "qryTest"
        .NamedParameters = True
        .Parameters.Append .CreateParameter("@username", adVarChar, adParamInput, 255, LCase(Environ("Username")))
        .Execute recordsAffected
    End With

2 个答案:

答案 0 :(得分:0)

通常,这类操作进入存储过程,但是在Acces / Excel女士中,您必须使用VBA。最简单的方法是,在更新之前先检索要更新的ID。

因此首先出现:将其保存在变量中

SELECT TOP 1 ID
FROM Table1 
WHERE Update_user Is Null 
ORDER BY Col2 DESC , ID

然后

update Table1
SET Table1.Update_time = Now(), Table1.Update_user = @username where Id = @idFromFirstQuery;

之后

select * from Table1 where Id = @idFromFirstQuery;

这样,您就知道要更新的ID。

或:

您还可以将now()转换为参数,并提供时间戳作为参数。 喜欢:

update (table selection ) set update_time = '2020-19-03 10:0=10:10', update_user = 'User1';

更新后,您可以执行以下操作: Select * from Table1 where update_user = 'User1' and update_time = '2020-19-03 10:0=10:10';

注意!,您强烈假设要提供的时间戳+用户名是唯一的。我个人不会使用这种方法。

答案 1 :(得分:-1)

不确定,但是如果您具有唯一的ID,则可以执行以下操作。这是在Access中完成的,因此需要建立连接,因为我认为可以。

Function sqlret() As String

Dim c As ADODB.Connection
Dim s As String
Dim r As ADODB.Recordset
Dim l As Long

Set c = CurrentProject.Connection

c.Execute "insert into tblprojects(projecttitle) values ('code1')"
Set r = New ADODB.Recordset
r.Open "select @@identity", c, 1
l = r.Fields(0).Value
r.Close

r.Open "select * from tblprojects where [projectid]=" & l, c, 1
sqlret = r.GetString

End Function