Link to home
Start Free TrialLog in
Avatar of Zbiebu
Zbiebu

asked on

Return ID to user

Hi,

How would I be able to return the value of an identity field to the user after inserting data.
Thanks
Avatar of selva_kongu
selva_kongu
Flag of India image

Asign the @@Identity into variable and return it via out param.

create proc(@Ident int out )
AS
BEGIN
insert into table ....

SET @Ident = @@IDENTITY

END
Avatar of Lowfatspread
don't use @@identity it doesn't return the value you desire ...

you need to use the scope_identity() function instead

for all sql server since sql 2000

declare @id int,@err int,@rows int

insert into yourtable (column list)
  select .....

select @err=@@error,@rows=@@rowcount,@id=scope_identity()

the identity value of the last row inserted by the previous insert statement in this scope will be retrieved...

this protects you from the actions of any triggers , which maybe invoked by the statement...

another method is to use the OUTOUT clause (which is a MS SQL extension)
Avatar of Zbiebu
Zbiebu

ASKER

ALTER PROCEDURE [dbo].[usp_InsertDetails]

	@Title VARCHAR(500),
	@Description VARCHAR(255),
	@Section VARCHAR(50),
	@CompiledBy VARCHAR(20),
	@Link VARCHAR(50),
	@Version INT,
	@Date SMALLDATETIME
AS

SET NOCOUNT ON;
SET @Version = 1

INSERT INTO Details
(Title, [Description], Section, CompiledBy,Link, Version,Date)
VALUES(@Title, @Description, @Section, @CompiledBy, @Link, @Version,@Date)

Open in new window


Hi Thanks for the reply.

Above is the code for the SP for insert,  where would I place the code you mention.
ASKER CERTIFIED SOLUTION
Avatar of selva_kongu
selva_kongu
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial