Ok, IMHO, the problem here is the use of WHILE EXISTS. Using SET has more serious problems. You should always use SELECT whenever you can, instead of SET.
If you're using SET to assign a value to a variable, and the SQL fails, the variable retains the previous value. NOT good! If you use SELECT, at least NULL will be assigned to the variable. FAR better.
--Quick and dirty example:
DECLARE @t varChar(25);
SET @t = 'Test 1';
--Some work here...
SET @t = 'Test 2' + ' ' + SELECT TOP 1 SomeSQLThatFails FROM someServer.dbo.SomeTable;
SELECT @t; -- THIS RETURNS 'Test 1' IF the SQL in your SET statement above fails.
SELECT @t = 'Test 2' + ' ' + SELECT TOP 1 SomeSQLThatFails FROM someServer.dbo.SomeTable;
SELECT @t; -- THIS returns NULL. Better NULL than some incorrect value.
--The SQL Whisperer
commented on Aug 10 2011 3:22PM