问题
So I have 2 Tables in one Database (Table1 and Table2). What I want to do is to get the last generated ID (which is primary key) from the first table (Table1) and add it to another table (Table2).
For example. The Last generated ID from Table1, column NRRENDOR is 25 (I have deleted the rows that's why it shows 22, it is primary key). If I add a row to Table1 it will generate number 26 on column NRRENDOR (First picture). But when number 26 is added to column NRRENDOR from Table 1, I want it to be added to Table2, column NRD too (Second Picture).
回答1:
You should use a sql-query like the one below after inserting the new element to the first table.
Insert into table2 (id) values(Select top 1 ID from table1 order by id desc)
This should work in sql-server 2008 and newer.
回答2:
From MySQL Reference Manual, 20.6.14.3 How to Get the Unique ID for the Last Inserted Row
INSERT INTO NRRENDOR (auto, field) VALUES(NULL, 'value');
generate ID by inserting NULL
INSERT INTO NRD (id, field) VALUES(LAST_INSERT_ID(), 'value');
use ID in second table.
Or you can get the last insert id manually executing the following query immediately after the INSERT into NRRENDOR
SELECT last_insert_id()
and use it later in your second INSERT query for NRD.
来源:https://stackoverflow.com/questions/23107570/get-last-generated-id-asp-net