Given the choice between your expression and the set
, I would choose the CTE. I find that using set
with a subquery somewhat icky. After all, the following does the same thing:
SELECT TOP 1 @viewtime = viewtime
FROM History
WHERE user_id = @user_id AND video_id = @video_id
ORDER BY viewtime ASC;
In other words, the set
is redundant.
In addition, separating the set
from the delete
introduces an opportunity for a race condition. Perhaps another query might insert a row or delete the one you are trying to delete.
As for the CTE itself, it is okay. You need the CTE (or subquery) if you are going to delete rows in a particular order.