Link to home
Start Free TrialLog in
Avatar of lobos
lobos

asked on

select count plus 1 and update it

I have a record in a table and I want to create a stored procedure that when invoked it will do a select on the record and get the value of counter, increment it by one update the record and return the new value.

is this possible with a stored proc?
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg 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
variant with output parameter:
CREATE PROCEDURE dbo.GetSequence
( @value int OUTPUT ) 
AS
 SET NOCOUNT ON
 BEGIN TRANSACTION
 SELECT @Value = yourfield + 1 FROM yourtable WHERE ...
 UPDATE yourtable SET yourfield = @value WHERE ...
 COMMIT

Open in new window

Create PROC advance_counter
@pk_col int
@new_value int = null output
AS
begin transaction
update your_table
set counter = counter + 1
where pk_col = @pk_col
select @new_value = counter
from your_table
where pk_col = @pk_col
commit transaction
Avatar of lobos
lobos

ASKER

how do I test this with query anylyser?
exec  GetSequence
Procedure 'GetSequence' expects parameter '@value', which was not supplied.

also why do I have to use an output parameter...can't I just use a select statement and then with that record I can get the value of the counter?
ie.
CREATE procedure GetSequence
as
Begin
select * from your_table      
end
GO

whats the difference, and how would I get that value if I was to use an output parameter...when using the select statement like above...I could just call and refence the column name....but not sure why and how it would be with the output parameter.
Use Angel's first response to get the value in the result set instead of an output parameter.  You haven't indicated how you are going to use this SP, so that's why a couple of different ways of doing it have been suggested.  For instance, if you are going to call this SP from another T-SQL batch or Stored Procedure then you will not be able to access the value if you just return it in a result set, but you would be able to get it from an output parameter.  If you are just going to call the SP from a Client-Side programming technology then using the Result Set version should be fine.
If this is SQL 2005 you could also do:

create proc usp_IncrementAndReturn @id int as
UPDATE mycol SET mycol=mycol+1 OUTPUT inserted.mycol WHERE id=@id
GO
the second example would be used like this in query analyser:

declare @value int
exec  GetSequence @value output
select @value result
Avatar of lobos

ASKER

thanks