Recently, I came across a client request in which they were asking to capitalize the first letter of each word in a column containing strings. My first thought was to find a solution without the use of loops or cursors. However, the requirement forces me to bring loops into the story.
I used 2 loops, the first of which is merely for iterating through the table. The second loop does the actual word. So, what it actually does is that in the first loop, it takes a row from the table in question and passes the string in that row to the 2nd loop, the 2nd loop searches for spaces. As soon as it encounters a space, it capitalizes the next alphabet until it iterates the whole string. Once the whole string has been updated, it writes the updated value back to the original table, hence, manipulating the data as per client request.
DECLARE @i INT = 1,
@count INT,
@i2 INT = 1,
@count2 INT,
@address nvarchar(50),
@query nvarchar(MAX)
CREATE TABLE #temp
(
N INT IDENTITY(1,1),
AddressID uniqueidentifier,
AddressOld nvarchar(50),
AddressNew nvarchar(50)
)
INSERT INTO #temp(AddressID, AddressOld, AddressNew)
SELECT AddressID, Address, LOWER(Address)
FROM dbo.Address
SELECT @count = COUNT(*)
FROM #temp
WHILE (@i <= @count)
BEGIN
SET @address = ''
SELECT @address = AddressNew
FROM #temp
WHERE N = @i
PRINT @address
SET @count2 = LEN(@address)
WHILE (@i2 <= @count2)
BEGIN
IF
(
SELECT SUBSTRING(@address, @i2, 1)
) = ' '
BEGIN
SET @address = STUFF(@address, @i2+1 , 1, UPPER(SUBSTRING(@address, @i2+1, 1)))
END
SET @i2 = @i2 + 1
END
UPDATE #temp
SET AddressNew = @address
WHERE N = @i
SET @i2 = 1
SET @i = @i + 1
END
UPDATE a
SET a.AddressNew = t.AddressNew
FROM #temp t JOIN Client.ClientAddress a ON t.AddressID = a.AddressID
--DROP TABLE #temp
Comments
Post a Comment