20

I have a table on my database. My table's name is "Company". I want to change data "company_name" as upper case first letter. For example;

"ABC COMPANY"

"DEF PLASTICITY"

as

"Abc Company"

"Def Plasticity"

I know that I should use "UPDATE" command. But How? Thanks for your help!

(CONCAT does not work)

TylerH
  • 20,799
  • 66
  • 75
  • 101
cethint
  • 2,231
  • 8
  • 28
  • 31
  • 3
    What you describe is called "Title Case" and is discussed here: http://stackoverflow.com/questions/9595356/proper-title-case-in-t-sql – Brian Jul 27 '12 at 12:56

7 Answers7

32

SQL Server Don't have Initcap function like oracle.

You can create UDF for Initcap.

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

Checking for UDF working

select [dbo].[InitCap] ('stackoverflow com');

Stackoverflow Com

you can update your table like this

update table
set column=[dbo].[InitCap](column);
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
11
update  YourTable
set     company_name = upper(substring(company_name,1,1)) + 
            lower(substring(company_name, 2, len(company_name)-1))
where   len(company_name) > 0

Live example at SQL Fiddle.

Andomar
  • 232,371
  • 49
  • 380
  • 404
  • 1
    Won't that only set the first letter capital. The SO wants the first letter of every word capital as far as I can tell – My Other Me Jul 27 '12 at 13:00
  • second word's first case is lower case. I want to do all words' first cases must be upper case. – cethint Jul 27 '12 at 13:01
2

With indebtedness to the above post, this function capitalizes the first letter of every word except those that are less than a certain character length, which are assumed to be acronyms. If that's no issue, then you set the second argument to 0.

CREATE function [dbo].[f_camel_exc_short_words] (@InputString varchar(4000),@AcronymMaxLen INT )
RETURNS VARCHAR(4000)
AS
BEGIN

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

SET @Word = ''
SET @OutputString = '' 
SET @Index = 1

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

    --IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
    --    SET @OutputString = @OutputString + @Char
        
    IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(','0','1','2','3','4','5','6','7','8','9') or @Index = LEN(@InputString)+1
    BEGIN
         SET @WordIndex = 1
        IF LEN(@Word) > @AcronymMaxLen 
        BEGIN
            WHILE @WordIndex <= LEN(@Word)
            BEGIN
                SET @WordChar = SUBSTRING(@Word,@WordIndex,1)
                if @WordIndex = 1  begin
                    SET @Word = STUFF(@Word,@WordIndex,1,UPPER(@WordChar))    end
                else    begin
                    SET @Word = STUFF(@Word,@WordIndex,1,LOWER(@WordChar))    end
                SET @WordIndex = @WordIndex + 1
            END
        END
        ELSE BEGIN
            SET @Word = UPPER(@Word)
        END
        set @OutputString = @OutputString + @Word
        SET @Word = ''
    END
    SET @Word = @Word + @Char
    SET @Index = @Index + 1
END  

return @OutputString

end
GO

So

PRINT dbo.f_camel_exc_short_words ('PIONEER EURO BOND FUND CLASS C (NON-DIST) (EUR) (OFFSHORE) ISIN LU0119429891',4)

returns

Pioneer EURO BOND FUND Class C (NON-Dist) (EUR) (Offshore) ISIN LU0119429891

TylerH
  • 20,799
  • 66
  • 75
  • 101
BrownsFan
  • 41
  • 2
1

With a little help of a split function like this one.

Try this, replace YourTable with whatever your table name is:

update T
set Name = P.Name
from YourTable as T
  cross apply (select (select upper(left(X.s, 1))+lower(stuff(X.s, 1, 1, ''))+' '
                       from dbo.split(' ', Name) as X
                       for xml path(''), type).value('.', 'varchar(50)')
              ) as P(Name)
Community
  • 1
  • 1
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
0

Try this:

declare @word as nvarchar (50)
set @word = 'ABC COMPANY'
select upper(left(@word, 1)) + lower(SUBSTRING(@word,2,charindex(' ', @word)-2)) + ' ' + 
upper(left(substring(@word,charindex(' ', @word)+1,len(@word)-1),1)) 
+ lower(SUBSTRING(@word,charindex(' ', @word)+2, len(@word)))
Myk Syk
  • 71
  • 8
0

A further modification handles possessives ('s) and words starting with Mc

if ' ' + @OutputString like '% Mc%'
set @OutputString = ' ' + @OutputString
set @index = CHARINDEX ( ' Mc', @OutputString)
while @Index > 0
begin
    set @OutputString = SUBSTRING(@outputString, 1, @index + 2) + UPPER(SUBSTRING(@outputString, @index + 3, 1)) + SUBSTRING(@outputString, @index + 4, len(@outputString))
    set @index = CHARINDEX ( ' Mc', @OutputString, @Index + 4)
end
set @outputstring = ltrim(rtrim(@outputstring))

if @OutputString + ' ' like '%''S %' 
set @OutputString = ltrim(rtrim(REPLACE(@outputstring + ' ', '''S ', '''s ')))

place right before Return

-1
CREATE FUNCTION Initcap
( @mystring varchar(50) )
RETURNS VARCHAR(50)
AS
BEGIN
   DECLARE @val VARCHAR(50);
   SET @val = (select upper(left(@mystring,1)) +  lower(substring(@mystring,2,datalength(@mystring)-1)) )
   RETURN @val;
END;
DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
user3183457
  • 97
  • 1
  • 2
  • It's better to include some context/explanation surrounding code as that makes the answer more useful to the OP and future readers (especially since this is an old question with several high-quality answers). Also, please be sure to use the code format feature (leave a blank line and then indent by four spaces) to improve readability. – EJoshuaS - Stand with Ukraine Jan 24 '17 at 21:09