How to do this so that there are no problems with connections, because in advance I don’t know what IDENTITY will be generated by the server.
This can be done as follows.
Suppose on the client side in the C # code we have tables
var table1 = new DataTable("Table1"); table1.Columns.Add("ID", typeof(int)); table1.Columns.Add("FileName", typeof(string)); var table2 = new DataTable("Table2"); table2.Columns.Add("ID", typeof(int)); table2.Columns.Add("ParentID", typeof(int)); table2.Columns.Add(...);
which we fill with some data. If the data is always new and on the SqlServer side are subject to unconditional insertion, then we generate any IDs. This will be a "temporary" ID.
We send the data table1 and table2 some way to the server (via table parameters, using SqlBulkCopy into temporary tables, or in some other way). Suppose that you send data to temporary tables #table1 and #table2 .
On the SqlServer side, in order to insert data into the first table, MERGE use MERGE with the OUTPUT clause, which will allow us to compare the temporary IDs we assigned with the actual ones. Then we insert the data into the second table using this mapping:
create table #map1 (TmpID int, ActualID int, primary key (TmpID)); merge into Table1 t using #table1 s on 1 = 0 when not matched then insert (FileName) values (s.FileName) output s.ID, inserted.ID into #map1 (TmpID, ActualID); insert into Table2 (ParentID, ...) select m1.ActualID, ... from #table2 t2 left join #map1 m1 on m1.TmpID = t2.ParentID; drop table #map1;
Also, other users can insert data into these tables (on the server). Will the logic of multi-use change, or can we abstract from it?
When multi-use no correction is required.