I have two similar tables on different databases.
Database1/TableA
Database2/TableA
I want to fetch a row from one table and insert it into other table on other server. Like:
Database1/TableA
Id State Name
500 OH John [Fetch this row]
Database2/TableA
Id State Name
1 OH John [Insert and fetch PK '1']
I tried this using bulkcopy and it works fine.
But problem is I need to get PK from the new insert as I need to populate another child table.
Is there any better way to achieve this? Please on C# code, no database linking or SQL queries. Just C# solutions. Or if query can be used in C# code that is fine. Any working example code with Dataset or Datarow will be great help.
Thanks!
First you need to get the row(s) from
Database.TableA. You could for example use aSqlDataAdapterwith aDataTableor aSqlDataReader.SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.