0

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?

3 Answers 3

2
UPDATE bk2_InfoPages
SET SortOrder = SortOrder - (SELECT COUNT(*) FROM Deleted d WHERE d.SortOrder <= bk2_InfoPages.SortOrder)
Sign up to request clarification or add additional context in comments.

1 Comment

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."
1

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

Comments

0

Hope this would work!

UPDATE bk2_InfoPages
SET SortOrder = SortOrder - subquery.c
FROM (
SELECT SortOrder, COUNT(*) AS c
FROM Deleted d
GROUP BY SortOrder
) AS subquery
WHERE subquery.SortOrder <= bk2_InfoPages.SortOrder;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.