SQL: 最初の文字のみ大文字にする [重複] 質問する

SQL: 最初の文字のみ大文字にする [重複] 質問する

各単語の最初の文字を大文字にする SQL ステートメントが必要です。他の文字は小文字にする必要があります。

単語は次のようになります。

wezembeek-oppem
roeselare
BRUGGE
louvain-la-neuve

それは次のようになります:

Wezembeek-Oppem
Roeselare
Brugge
Louvain-La-Neuve

これは UPDATE ステートメントを使用する必要があり、列のデータを更新したいと思います。ご回答をよろしくお願いいたします。私は SQL 初心者です。

ベストアンサー1

列自体の名前を変更したいですか、それとも列内のデータを大文字にしたいですか? 変更する必要があるデータの場合は、以下を使用します:

UPDATE [yourtable]
SET word=UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word)))

表示のみを変更し、テーブル内の実際のデータを変更する必要がない場合は、次のようにします。

SELECT UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word))) FROM [yourtable]

編集: 「-」について気づいたので、関数でこの問題を解決しようと試みました。

CREATE FUNCTION [dbo].[CapitalizeFirstLetter]
(
--string need to format
@string VARCHAR(200)--increase the variable size depending on your needs.
)
RETURNS VARCHAR(200)
AS

BEGIN
--Declare Variables
DECLARE @Index INT,
@ResultString VARCHAR(200)--result string size should equal to the @string variable size
--Initialize the variables
SET @Index = 1
SET @ResultString = ''
--Run the Loop until END of the string

WHILE (@Index <LEN(@string)+1)
BEGIN
IF (@Index = 1)--first letter of the string
BEGIN
--make the first letter capital
SET @ResultString =
@ResultString + UPPER(SUBSTRING(@string, @Index, 1))
SET @Index = @Index+ 1--increase the index
END

-- IF the previous character is space or '-' or next character is '-'

ELSE IF ((SUBSTRING(@string, @Index-1, 1) =' 'or SUBSTRING(@string, @Index-1, 1) ='-' or SUBSTRING(@string, @Index+1, 1) ='-') and @Index+1 <> LEN(@string))
BEGIN
--make the letter capital
SET
@ResultString = @ResultString + UPPER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--increase the index
END
ELSE-- all others
BEGIN
-- make the letter simple
SET
@ResultString = @ResultString + LOWER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--incerase the index
END
END--END of the loop

IF (@@ERROR
<> 0)-- any error occur return the sEND string
BEGIN
SET
@ResultString = @string
END
-- IF no error found return the new string
RETURN @ResultString
END

したがって、コードは次のようになります。

UPDATE [yourtable]
SET word=dbo.CapitalizeFirstLetter([STRING TO GO HERE])

おすすめ記事