Header Ads Widget

Capitalizar primera letra de las palabras con SQL Server y Oracle

 


Una característica que podrían solicitarte en aglún momento es la de capitalizar las palabras de una oración. 

Es decir si una palabra es "el cuaderno rojo" debemos transformarlo en "El Cuaderno Rojo". 

Anteriormente ya hemos visto como hacerlo en C# ahora veremos como hacerlo en SQL Server y en Oracle
>
Para Oracle existe la función INITCAP():
INITCAP(string)
La función INITCAP convierte la primera letra de cada palabra a mayúsculas y las demás letras a minúsculas. Es decir podemos capitalizar una oración con lo siguiente:

SELECT 
	INITCAP('CaPITaliZAR una ORaciÓN')
FROM
	DUAL;
Lo que mostrará el siguiente resultado:
es-PE
Capitalizar una oración
Espero les ayude.
Para el caso de SQL Server, es un poco más complicado, no existe una función igual a INITCAP. Sin embargo hace unos años, Jeff Moden, un conocido maestro del SQL, adaptó una función que hace el trabajo (comentarios en inglés, tengan cuidado con COLLATION):

CREATE FUNCTION dbo.InitialCap(@String VARCHAR(8000))
/***************************************************************************************************
 Purpose:
 Capitalize any lower case alpha character which follows any non alpha character or single quote.

 Revision History:
 Rev 00 - 24 Feb 2010 - George Mastros - Initial concept
 http://blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/sql-server-proper-case-function

 Rev 01 - 25 Sep 2010 - Jeff Moden 
        - Redaction for personal use and added documentation.
        - Slight speed enhancement by adding additional COLLATE clauses that shouldn't have mattered
        - and the reduction of multiple SET statements to just 2 SELECT statements with only one
        - actually appearing in the loop, which means only 1 PATINDEX is now in the loop (DRY Code).
        - Add no-cap single-quote by single-quote to the filter.
***************************************************************************************************/
RETURNS VARCHAR(8000)
     AS
  BEGIN 
----------------------------------------------------------------------------------------------------
DECLARE @Position INT
;
--===== Update the first character no matter what and then find the next postion that we 
     -- need to update.  The collation here is essential to making this so simple.
     -- A-z is equivalent to the slower A-Z
 SELECT @String   = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
        @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin)
;
--===== Do the same thing over and over until we run out of places to capitalize.
     -- Note the reason for the speed here is that ONLY places that need capitalization
     -- are even considered for @Position using the speed of PATINDEX. 
  WHILE @Position > 0
 SELECT @String   = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
        @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin)
;
----------------------------------------------------------------------------------------------------
 RETURN @String;
    END
; 

Espero les ayude en las próximas tareas de programación...¡Y que no sólo les funcione en su computadora!

Publicar un comentario

0 Comentarios