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.
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.
When you use "IMDECONP38" then you break SCOPE_IDENTITY because
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
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
For sql server 2012, to get the name of the identity column
select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns
join sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id
where sys.all_objects.object_id = object_id('system_files')
If you have a Linked server you can use this:
select iden.name as id
from [LINKED_SERVER_NAME].[DATABASE_NAME].sys.identity_columns as iden
join [LINKED_SERVER_NAME].[DATABASE_NAME].sys.all_objects allobj
on iden.object_id = allobj.object_id
where allobj.name = 'TABLE NAME HERE'
select @@IDENTITY AS 'variablename'
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.