I have this as the first part of a stored procedure:
DECLARE @_id as int
if exists(select 1 from JTrack_Visitors WHERE cookie = @cookie)
begin
UPDATE JTrack_Visitors
SET LastSeen = @_now
WHERE cookie = @cookie
end
else
begin
INSERT INTO JTrack_Visitors(Cookie, CreatedOn, LastSeen)
VALUES (@cookie, @_now, @_now)
end
How can I set @_id
to be the identity of the row either being inserted or updated? I need that value to use later in the stored procedure.
Thanks.
You can make use of OUTPUT clause in your both statements, in either case populate a table variable and later retrieve value from that table variable.
DECLARE @_id as int;
DECLARE @ID_Table TABLE(ID INT);
IF EXISTS (select 1 from JTrack_Visitors WHERE cookie = @cookie)
BEGIN
UPDATE JTrack_Visitors
SET LastSeen = @_now
OUTPUT inserted.ID INTO @ID_Table(ID)
WHERE cookie = @cookie
END
ELSE
BEGIN
INSERT INTO JTrack_Visitors(Cookie,CreatedOn,LastSeen)
OUTPUT inserted.ID INTO @ID_Table(ID)
VALUES (@cookie,@_now,@_now)
END
SELECT @_id = ID FROM @ID_Table;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments