Reputation: 127
I have a table with a Comments field and I want to capitalize the first letter of the string in each record eg change 'duplicate' into 'Duplicate'. Some records will already have a capital at the start, and some may even be a number.
I tried this
SELECT UPPER(LEFT(Comments,1))+SUBSTRING(Comments,2,LEN(Comments)) FROM dbo.Template_Survey
but it fails because my field is an 'ntext' type.
It would also be useful to be able to capitalize the first letter after a full stop (period) but this is not essential unless someone has the code already written.
Thanks in advance.
Upvotes: 2
Views: 30073
Reputation: 165
or:
UPDATE `table` SET name = CONCAT(UPPER(LEFT(name,1)),LOWER(RIGHT(name,LENGTH(name)-1)))
Upvotes: 1
Reputation: 44326
A bit late on my post here, but this solution is shorter. This works in sql server 2008+:
SELECT
UPPER(CAST(Comments as nchar(1)))+LOWER(STUFF(CAST(Comments as nvarchar(max)),1,1,''))
FROM dbo.Template_Survey
Upvotes: 0
Reputation: 19863
Cast you column to nvarchar(max)
here is the working example
http://sqlfiddle.com/#!3/5dd26/3
To update records you can use:
Update dbo.Template_Survey
set Comments = UPPER(LEFT(cast(Comments as nvarchar(max)),1)) +
LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2,
LEN(cast(Comments as nvarchar(max)))))
Upvotes: 2
Reputation: 2755
Cast your ntext to nvarchar(max) and do the upper and left operations. Sample below.
SELECT UPPER(LEFT(cast(Comments as nvarchar(max)),1)) +
LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2,
LEN(cast(Comments as nvarchar(max)))))
FROM dbo.Template_Survey;
Following should work for update.
Update dbo.Template_Survey SET Comments =
UPPER(LEFT(cast(Comments as nvarchar(max)),1)) +
LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2,
LEN(cast(Comments as nvarchar(max)))));
Upvotes: 4