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
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With