Fonction InitCap pour SQL Server

Pour ceux qui ne la connaissent pas, la fonction InitCap permet sous Oracle de remplacer la première lettre de chaque mot dans un string par une majuscule; les autres lettres sont  en minuscule. Voici une fonction définie par l’usager pour simuler la fonction InitCap sous SQL Server.

J’utilise cette fonction depuis déjà longtemps au travail; je ne me souviens malheureusement pas à qui revient les mérites de la fonction originale…

CREATE FUNCTION [dbo].[initcap] (@text varchar(4000))
RETURNS varchar(4000) AS BEGIN DECLARE    @counter INT,
@length INT,
@char CHAR(1),
@textnew VARCHAR(4000)

IF @text <> ''

BEGIN

SET @text = RTRIM(@text)
SET @text = LOWER(@text)
SET @length = LEN(@text)
SET @counter = 1
SET @text = UPPER(LEFT(@text, 1) ) + RIGHT(@text, @length - 1)

WHILE @counter <> @length

BEGIN

SELECT @char = substring(@text, @counter, 1)
IF @char = space(1)  OR @char =  '_' OR @char = ','  OR @char = '.' OR @char = '\'
OR @char = '/' OR @char = '(' OR @char = ')' OR @char = '-'

BEGIN

SET @textnew = LEFT(@text, @counter) + upper(substring(@text, @counter+1, 1)) + RIGHT(@text, (@length - @counter) - 1)
SET @text = @textnew

END

SET @counter = @counter + 1

END

END

RETURN @text END

Leave a Reply

Your email address will not be published. Required fields are marked *