Wednesday, March 7, 2012

Returning timestamp from inserted record using @@Identity

i recently found a little error in a stored procedure that was included in a project handed over to me....
the sp was rather simple. it just inserted a record into a table and returned the identity and the timestamp as follows

IF @.@.ERROR>0
BEGIN
SELECT @.int_InterventionID = 0
RETURN @.@.ERROR
END
ELSE
BEGIN
SELECT @.int_InterventionIDReturned = MAX(InterventionID) FROM tblIntervention
SELECT @.ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @.int_InterventionIDReturned
SELECT @.int_InterventionID = @.int_InterventionIDReturned, @.ts_Timestamp = @.ts_TimestampReturned
RETURN 0
END

i figured that it should be using @.@.Identity for the interventionIdentity rather than max(InterventionID)

so i changed to...

IF @.@.ERROR>0
BEGIN
SELECT @.int_InterventionID = 0
RETURN @.@.ERROR
END
ELSE
BEGIN
SELECT @.int_InterventionIDReturned = @.@.IDENTITY
SELECT @.ts_TimestampReturned = [Timestamp] FROM tblIntervention WHERE InterventionID = @.int_InterventionIDReturned
SELECT @.int_InterventionID = @.int_InterventionIDReturned, @.ts_Timestamp = @.ts_TimestampReturned
RETURN 0
END
it returns the @.int_InterventionIDReturned but the timestamp now comes back as null? why?
how can i ensure that i always get the timestamp of the record it has just inserted
any help greatly appreciated,
Cheers,
Craig

Craig:

Try to use SCOPE_IDENTITY() instead of @.@.identity or Max (InterventionID).

Dave

|||nice one, that work perfectly.
Cheers,
Craig

No comments:

Post a Comment