Access SQL: Get the identity value of the affected record from an insert statement Or From a DAO.QueryDef

核能气质少年 提交于 2019-12-25 00:28:19

问题


I have to convert some SQL queries to access SQL. Some of them use @@identity to insert two linked records into two different tables. Unfortunately, an access query can only contain one statement(i.e. I can not select @@identity after the insert statement).

This is not possible:

insert into table1 (values)
  select values from table1 where id=@id;
select @@identity;

This example statement is supposed to Copy a record from Table1 to a new record in the said table and then do the same in Table2, referencing the new record from Table1.

Here's what the sql query looks like:

        INSERT INTO Table1 ( some_value, the_other_values)
        SELECT  @new_value as some_value, the_other_values
        FROM    Table1
        WHERE   id = @oldID

        SELECT @New_id = @@identity

        INSERT INTO     Table2 ( idP, other_values)
            SELECT  @New_id AS idP, other_values
            FROM    Table2
            WHERE   (idP = @Old_id)

I tried to do this in two statements, using vba, but I have found no way to access @@identity from the other query.

Here's the vba - I omitted the declarations, the actual code is a loop but this is the important part:

Set qdf = CurrentDb.QueryDefs("first_part_of_query")
        qdf!New_id = userInput_newID
        qdf!oldID = userInput_oldID
        qdf.Execute
        Set qdf = CurrentDb.QueryDefs("second_part_of_query")
        qdf!New_id = the_identityvalue 'WHAT DO I SET THIS TO?
        qdf.Execute

回答1:


You need to use a single instance of your database, and then you can just use OpenRecordset("SELECT @@IDENTITY") to obtain the identity value.

Dim db As DAO.Database
Set db = CurrentDb
Set qdf = db.QueryDefs("first_part_of_query")
qdf!New_id = userInput_newID
qdf!oldID = userInput_oldID
qdf.Execute
Set qdf = db.QueryDefs("second_part_of_query")
qdf!New_id = db.OpenRecordset("SELECT @@IDENTITY").Fields(0)
qdf.Execute


来源:https://stackoverflow.com/questions/50016139/access-sql-get-the-identity-value-of-the-affected-record-from-an-insert-stateme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!