I’m trying to remove the first character in LastNames that start with a space. The code below seems to clear LastName entirely, making the field empty. Do you see something wrong?
DECLARE @Id int
DECLARE @LastName NVARCHAR(255)
while (SELECT COUNT(*) FROM [Table] WHERE LastName LIKE ' %') > 0
Begin
Select Top 1 @Id = Id, @LastName = LastName FROM [Table] WHERE LastName LIKE ' %'
UPDATE [Table] SET LastName = SUBSTRING(@LastName, 1, LEN(@LastName)) WHERE Id = @Id
End
For me the code you posted runs in an infinite loop.
LastName = SUBSTRING(LastName, 1, LEN(LastName))will have no effect other than removing right trailing space (as that is not counted byLEN). To remove the left most character you would needSUBSTRING(LastName, 2, LEN(LastName) - 1).But, you don’t need a RBAR (Row By Agonizing Row) loop here just use
to update all matching rows in a set based way.