Tuesday, 27 August 2013

Update Trigger conditional values

Update Trigger conditional values

I have been searching around stackoverflow but I have not found what I'm
looking for. I have a Sql Server Database. One table with a field
"Priority" I would like to update on every insert or update.
The problem is that I want to perform a Priority pile using this rules:
1.-If the value I try to insert has a prority value that already exists
then every consecutive row in the table must change its priority value
adding 1. 2.-If the value I try to insert has a priority that not exists
then the trigger does nothing.
This is the trigger I haver built:
ALTER trigger [Priority]
on [dbo].[TBL_PILA]
after insert, update
AS
declare @priority int;
declare @reg_id int;
SELECT @reg_id =i.id from inserted i;
SELECT @priority =PRIORITY from TBL_PILA where ID =@reg_id
-- perform update here in TBL_PILA table
UPDATE TBL_PILA SET PRIORITY=PRIORITY+1 WHERE ID <>@reg_id AND
PRIORITY>=@priority
GO
The problem is whenever exists a few consecutive values and one not
consecutive value the trigger must stops. Example Priority 1 2 4 5 6 8
If I try to insert a row with priority=3 the result should be: 1 2 3 4 5 6 8
Then If I try to insert a row with priority=4 then the result should be: 1
2 3 4 (inserted value) 5 (4+1) 6 (5+1) 7 (6+1) 8
But using the trigger I built I get this: 1 2 3 4 5 6 7 9 (8+1)

No comments:

Post a Comment