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\"
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.
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
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;
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)))
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);
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)