Quel est le meilleur moyen pour mettre en majuscule la première lettre de chaque mot dans une chaîne de caractères dans SQL Server

StackOverflow https://stackoverflow.com/questions/55054

  •  09-06-2019
  •  | 
  •  

Question

Quel est le meilleur moyen pour mettre en majuscule la première lettre de chaque mot dans une chaîne de caractères dans SQL Server.

Était-ce utile?

La solution

À partir de http://www.sql-server-helper.com/functions/initcap.aspx

CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) 
RETURNS VARCHAR(4000)
AS
BEGIN

DECLARE @Index          INT
DECLARE @Char           CHAR(1)
DECLARE @PrevChar       CHAR(1)
DECLARE @OutputString   VARCHAR(255)

SET @OutputString = LOWER(@InputString)
SET @Index = 1

WHILE @Index <= LEN(@InputString)
BEGIN
    SET @Char     = SUBSTRING(@InputString, @Index, 1)
    SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
                         ELSE SUBSTRING(@InputString, @Index - 1, 1)
                    END

    IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
    BEGIN
        IF @PrevChar != '''' OR UPPER(@Char) != 'S'
            SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
    END

    SET @Index = @Index + 1
END

RETURN @OutputString

END
GO

Il est plus simple/plus petit ici (mais ne fonctionne pas si une ligne n'ont pas les espaces, "Invalide la longueur de paramètre passé à la fonction DROITE."):

http://www.devx.com/tips/Tip/17608

Autres conseils

Une variante de celle que j'ai utilisé pendant un certain temps est:

CREATE FUNCTION [widget].[properCase](@string varchar(8000)) RETURNS varchar(8000) AS
BEGIN   
    SET @string = LOWER(@string)
    DECLARE @i INT
    SET @i = ASCII('a')
    WHILE @i <= ASCII('z')
    BEGIN
        SET @string = REPLACE( @string, ' ' + CHAR(@i), ' ' + CHAR(@i-32))
        SET @i = @i + 1
    END
    SET @string = CHAR(ASCII(LEFT(@string, 1))-32) + RIGHT(@string, LEN(@string)-1)
    RETURN @string
END

Vous pouvez facilement modifier pour gérer les caractères après les éléments autres que les espaces, si vous vouliez.

Une autre solution sans l'aide de la boucle - pur, basés sur l'approche avec une expression de table commune récursive

create function [dbo].InitCap (@value varchar(max))
returns varchar(max) as
begin

    declare
        @separator char(1) = ' ',
        @result varchar(max) = '';

    with r as (
        select value, cast(null as varchar(max)) [x], cast('' as varchar(max)) [char], 0 [no] from (select rtrim(cast(@value as varchar(max))) [value]) as j
        union all
        select right(value, len(value)-case charindex(@separator, value) when 0 then len(value) else charindex(@separator, value) end) [value]
        , left(r.[value], case charindex(@separator, r.value) when 0 then len(r.value) else abs(charindex(@separator, r.[value])-1) end ) [x]
        , left(r.[value], 1)
        , [no] + 1 [no]
        from r where value > '')

    select @result = @result +
    case
        when ascii([char]) between 97 and 122 
            then stuff(x, 1, 1, char(ascii([char])-32))
        else x
    end + @separator
    from r where x is not null;

    set @result = rtrim(@result);

    return @result;
end

Ici est la plus simple ligne de code.

select 
        LEFT(column, 1)+ lower(RIGHT(column, len(column)-1) )
     from [tablename]

Si vous êtes à la recherche de la réponse à la même question dans Oracle/PLSQL, alors vous pouvez utiliser la fonction INITCAP.Ci-dessous est un exemple de l'attribut dname à partir d'une table département qui a les valeurs ("ventes", "gestion", la "production", "développement").

SQL> select INITCAP(dname) from department;

INITCAP(DNAME)
--------------------------------------------------
Sales
Management
Production
Development

Comme une fonction table:

CREATE FUNCTION dbo.InitCap(@v AS VARCHAR(MAX))
RETURNS TABLE
AS
RETURN 
WITH a AS (
    SELECT (
        SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()'
        FROM string_split(@v, ' ')
        FOR XML PATH (''), TYPE) ret)

SELECT CAST(a.ret AS varchar(MAX)) ret from a
GO

Notez que string_split nécessite COMPATIBILITY_LEVEL 130.

BEGIN
DECLARE @string varchar(100) = 'asdsadsd asdad asd'
DECLARE @ResultString varchar(200) = ''
DECLARE @index int = 1
DECLARE @flag bit = 0
DECLARE @temp varchar(2) = ''
WHILE (@Index <LEN(@string)+1)
BEGIN
    SET @temp = SUBSTRING(@string, @Index-1, 1)
    --select @temp
    IF @temp = ' ' OR @index = 1
        BEGIN
            SET @ResultString = @ResultString + UPPER(SUBSTRING(@string, @Index, 1))
        END
    ELSE
        BEGIN

            SET @ResultString = @ResultString + LOWER(SUBSTRING(@string, @Index, 1)) 
        END 

    SET @Index = @Index+ 1--increase the index
END
SELECT @ResultString

FIN

Pour l'anglais uniquement des données.

Super non efficace du point de vue de la performance, mais efficace, du point de vue de la productivité.L'utiliser comme un convertisseur de temps:

SELECT 
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(

UPPER(LEFT(City,1))+LOWER(SUBSTRING(City,2,LEN(City)))

,' a', ' A')
,' b', ' B')
,' c', ' C')
,' d', ' D')
,' e', ' E')
,' f', ' F')
,' g', ' G')
,' h', ' H')
,' i', ' I')
,' j', ' J')
,' k', ' K')
,' l', ' L')
,' m', ' M')
,' n', ' N')
,' o', ' O')
,' p', ' P')
,' q', ' Q')
,' r', ' R')
,' s', ' S')
,' t', ' T')
,' u', ' U')
,' v', ' V')
,' w', ' W')
,' x', ' X')
,' y', ' Y')
,' z', ' Z')


FROM [Dictionaries].[dbo].[Cities]
  WHERE Country = 'US' AND City like '% %'
  ORDER BY City

Je cherchais le meilleur moyen de capitaliser et je recréer simple script sql

comment utiliser SELECT dbo.Capitalyze('ceci est un test avec plusieurs espaces")

suite "Ceci Est Un Test Avec Plusieurs Espaces"

CRÉER la FONCTION Capitalyze(@input de type varchar(100) ) retourne varchar(100) comme commencer

declare @index int=0
declare @char as varchar(1)=' '
declare @prevCharIsSpace as bit=1
declare @Result as varchar(100)=''

set @input=UPPER(LEFT(@input,1))+LOWER(SUBSTRING(@input, 2, LEN(@input)))
set @index=PATINDEX('% _%',@input)
if @index=0
    set @index=len(@input)
set @Result=substring(@input,0,@index+1)

WHILE (@index < len(@input))
BEGIN
    SET @index = @index + 1
    SET @char=substring(@input,@index,1)
    if (@prevCharIsSpace=1)
    begin
        set @char=UPPER(@char)
        if (@char=' ')
            set @char=''
    end

    if (@char=' ')
        set @prevCharIsSpace=1
    else
        set @prevCharIsSpace=0

    set @Result=@Result+@char
    --print @Result
END
--print @Result
return @Result

fin

fname est le nom de la colonne si fname valeur est akhil alors SUPÉRIEURE(à gauche(fname,1)) pour fournir le capital de la Première lettre(A) et la fonction de sous-chaîne SUBSTRING(fname,2,LEN(fname)) fournir(khil) concate à la fois à l'aide de + alors le résultat est (Akhil)

select UPPER(left(fname,1))+SUBSTRING(fname,2,LEN(fname)) as fname
FROM [dbo].[akhil]

Vous devriez essayer ceci à la place

Select INITCAP(column_name) from table_name;

Cela permettra de mettre en majuscule la première lettre des attributs des entrées.

IF OBJECT_ID ('dbo.fnCapitalizeFirstLetterAndChangeDelimiter') IS NOT NULL
    DROP FUNCTION dbo.fnCapitalizeFirstLetterAndChangeDelimiter
GO

CREATE FUNCTION [dbo].[fnCapitalizeFirstLetterAndChangeDelimiter] (@string NVARCHAR(MAX), @delimiter NCHAR(1), @new_delimeter NCHAR(1))
RETURNS NVARCHAR(MAX)
AS 
BEGIN
    DECLARE @result NVARCHAR(MAX)
    SELECT @result = '';
    IF (LEN(@string) > 0)
        DECLARE @curr INT
        DECLARE @next INT
        BEGIN
            SELECT @curr = 1
            SELECT @next = CHARINDEX(@delimiter, @string)
            WHILE (LEN(@string) > 0)
                BEGIN
                    SELECT @result = 
                        @result + 
                        CASE WHEN LEN(@result) > 0 THEN @new_delimeter ELSE '' END +
                        UPPER(SUBSTRING(@string, @curr, 1)) + 
                        CASE 
                            WHEN @next <> 0 
                            THEN LOWER(SUBSTRING(@string, @curr+1, @next-2))
                            ELSE LOWER(SUBSTRING(@string, @curr+1, LEN(@string)-@curr))
                        END
                    IF (@next > 0)
                        BEGIN
                            SELECT @string = SUBSTRING(@string, @next+1, LEN(@string)-@next)
                            SELECT @next = CHARINDEX(@delimiter, @string)
                        END
                    ELSE
                        SELECT @string = ''
                END
        END
    RETURN @result
END
GO
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top