Need to create SQL Server Stored Proc to increment or decrement a column value

hi - I want to call a stored procedure from C# and pass it 2 values. ID and Action.

Action will be decrement or increment.

I want to find row in table and decrement a column value or increment the value depending on the action.

I also need to lock the current value so that other users can't change it in between my read and update.

I'd like as much as possible in the stored procedure.

Many thanks

Chris
themagicmagicianAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
momi_sabagConnect With a Mentor Commented:
create procedure myProc (@id int, @action varchar(3))
as
update mytable
set  my_column = case when @action = 'INC' then my_column+1
                                     when @action = 'DEC' then my_column-1
       else my_column end
where my_column = @id
0
 
themagicmagicianAuthor Commented:
Thanks.

 Will this prevent other users from updating the value between read and write?

Will I get access denied errors if another user calls the stored procedure at the same time?

Regards
Chris
0
 
Anurag ThakurTechnical ManagerCommented:
just calling the stored procedure will not prevent others from doing a dirty read
to prevent that you need to do a locking mechanism i.e. transactions - when you are updating the value only you are updating and no one else

transactions dont prevent other users from modifying what one user has already modified - so in such a case a modified time stamp comes in picture
when a user fetches data from the database the modified time stamp is also returned and when the user comes in to update the database the time stamp is returned back and compared in the stored procedure so that any other user has not modified the data - if its not modified then you update else you return the error back to the user saying that please update as the data has been modified
0
 
momi_sabagCommented:
the code i posted will prevent concurrent updates by users because sql server perform data locking when you update a record
the entire update operation is an atomic process
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.