Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get identity of inserted row in Linked server?

I am inserting record in a remote Sql Server using Linked server, Now I wanna get the id of inserted record. something like scope_identity() in local server. My remote sql server is 2000 version.

I have seen this post but I can't add any stored procedures in remote sql server

like image 767
Raymond Morphy Avatar asked Apr 18 '11 21:04

Raymond Morphy


People also ask

How do I get the inserted row id in SQL Server?

Use SCOPE_IDENTITY() if you are inserting a single row and want to retrieve the ID that was generated. Use the OUTPUT clause if you are inserting multiple rows and need to retrieve the set of IDs that were generated.

What is @@ identity used for?

After an INSERT, SELECT INTO, or bulk copy statement is completed, @@IDENTITY contains the last identity value that is generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL.

How do I get the last inserted row id in SQL Server?

To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.


1 Answers

You could use the remote side's sp_executesql:

DECLARE @ScopeIdentity TABLE (ID int);
INSERT INTO @ScopeIdentity
EXEC server.master..sp_executesql N'
  INSERT INTO database.schema.table (columns) VALUES (values);
  SELECT SCOPE_IDENTITY()';
SELECT * FROM @ScopeIdentity;

Alternatively, you could use OPENQUERY:

SELECT *
FROM OPENQUERY(server, '
  INSERT INTO database.schema.table (columns) VALUES (values);
  SELECT SCOPE_IDENTITY() AS ID');
like image 69
Andriy M Avatar answered Oct 25 '22 01:10

Andriy M