I read an answer that said you don't want to use WHILE loops in SQL Server. I don't understand that generalization. I'm fairly new to SQL so I might not understand the explanation yet. I also read that you don't really want to use cursors unless you must. The search results I've found are too specific to the problem presented and I couldn't glean useful technique from them, so I present this to you.
What I'm trying to do is take the values in a client file and shorten them where necessary. There are a couple of things that need to be achieved here. I can't simply hack the field values provided. My company has standard abbreviations that are to be used. I have put these in a table, Abbreviations. the table has the LongName and the ShortName. I don't want to simply abbreviate every LongName in the row. I only want to apply the update as long as the field length is too long. This is why I need the WHILE loop.
My thought process was thus:
CREATE FUNCTION [dbo].[ScrubAbbrev]
(@Field nvarchar(25),@Abbrev nvarchar(255))
RETURNS varchar(255)
AS
BEGIN
DECLARE @max int = (select MAX(stepid) from Abbreviations)
DECLARE @StepID int = (select min(stepid) from Abbreviations)
DECLARE @find varchar(150)=(select Longname from Abbreviations where Stepid=@stepid)
DECLARE @replace varchar(150)=(select ShortName from Abbreviations where Stepid=@stepid)
DECLARE @size int = (select max_input_length from FieldDefinitions where FieldName = 'title')
DECLARE @isDone int = (select COUNT(*) from SizeTest where LEN(Title)>(@size))
WHILE @StepID<=@max or @isDone = 0 and LEN(@Abbrev)>(@size) and @Abbrev is not null
BEGIN
RETURN
REPLACE(@Abbrev,@find,@replace)
SET @StepID=@StepID+1
SET @find =(select Longname from Abbreviations where Stepid=@stepid)
SET @replace =(select ShortName from Abbreviations where Stepid=@stepid)
SET @isDone = (select COUNT(*) from SizeTest where LEN(Title)>(@size))
END
END
Obviously the RETURN should go at the end, but I need to reset the my variables to the next @stepID, @find, and @replace.
Is this one of those times where I'd have to use a cursor (which I've never yet written)?