views:

181

answers:

2

I have the following SQL statement in a trigger that fires on deletion:

UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= SortOrder)

My problem is that the very last SortOrder refers to the Deleted table and not to the bk2_InfoPages table. I am not allowed to add an alias to the bk2_InfoPages table because it's an UPDATE statement - so what should I do instead?

+2  A: 
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= bk2_InfoPages.SortOrder)
Yawar
Unfortunately I got the following error message when trying to execute the ALTER TRIGGER statement: "The multi-part identifier "bk2_InfoPages.SortOrder" could not be bound."
Tomas Lycken
+1  A: 

This should work:

UPDATE b
SET SortOrder = SortOrder - 
  (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= b.SortOrder)
from bk2_InfoPages b

You have to alias your table to do sub queries, for example:

-- this executes fine 
create table #t ( t int)

update t 
set t = (select count(*) from #t t1 where t.t = t1.t)
from #t t
Sam Saffron
That did the trick! Thanks! =)
Tomas Lycken