views:

260

answers:

5

I have a query like below

declare @str_CustomerID int
Insert into IMDECONP38.[Customer].dbo.CustomerMaster
( CustomerName , CustomerAddress , CustomerEmail , CustomerPhone )
values ( ‘werw12e’ , ‘jkj12kj’ , ‘3212423sdf’ , ‘1212121′
)

select @str_CustomerID= scope_identity()

After execution it returns null in my parameter.

I want to get the value of identity. How can I do that?

The main issue over here is "IMDECONP38" - the server name that I used. If I remove this I can get the value of identity in my parameter.

A: 
select @@IDENTITY AS 'variablename'
David
using `@@IDENTITY` is dangerous because it returns the lastID generated from any scope.
James
Lordy. Never use @@IDENTITY
gbn
i have realized the error of my ways. no more downvotes!
David
@David, I've never wanted to upvote a comment multiple times until now.
John Buchanan
+2  A: 

When you use "IMDECONP38" then you break SCOPE_IDENTITY because

  • the INSERT scope is now on the IMDECONP38 linked server
  • SCOPE_IDENTITY runs on the local server, not IMDECONP38

If on SQL Server 2005, try the OUTPUT clause but I'm not sure how it works for a linked server call

Insert into IMDECONP38.[Customer].dbo.CustomerMaster
OUTPUT INSERTED.ID   --change as needed
( CustomerName , CustomerAddress , CustomerEmail , CustomerPhone )
values ( ‘werw12e’ , ‘jkj12kj’ , ‘3212423sdf’ , ‘1212121′
)

Edit: Prutswonder said it first: use a stored proc on the linked server

gbn
Sql server giving error :Remote tables are not allowed to be the target of a DML statement with an OUTPUT clause, or the target of the INTO clause.
Pranay Rana
A: 

Please check if there are any triggers set for your table. This will cause a problem when you use SCOPE_IDENTITY() to get the last inserted identity field.

HTH

Raja
SET NOCOUNT ON does not affect SCOPE_IDENTITY. Or do you have an MSDN reference to back this up. As my question notes, only DataAdaptors can be affected by SET NOCOUNT ON here http://stackoverflow.com/questions/1483732/set-nocount-on-usage
gbn
@gbn: I had this same problem and SET NoCount OFF did the trick for me. Anyways I have taken that out of my answer :-).
Raja
Triggers affect the value of @@Identity not scope_identity()
HLGEM
+7  A: 

See this old question for a similar problem: You cannot retrieve a scoped variable like SCOPE_IDENTITY() from another server. Instead, you should use a stored procedure on the remote server to achieve this.

Prutswonder
Good call. Best advice so far.
gbn
+1  A: 

Use a stored procedure in the remote database.

CREATE PROCEDURE InsertCustomer (@name varchar(100), @address varchar(100), 
    @email varchar(100), @phone varchar(100), @id int OUT)
AS
    INSERT INTO dbo.CustomerMaster 
    (CustomerName , CustomerAddress , CustomerEmail , CustomerPhone ) 
    VALUES (@name, @address, @email, @phone)

    SET @id = SCOPE_IDENTITY()
GO

DECLARE @id int
EXEC IMDECONP38.Customer.dbo.InsertCustomer 'Fred','Bedrock','a@b','5',@id OUT
GO
Anthony Faull