gpt4 book ai didi

SQL:仅大写第一个字母

转载 作者:行者123 更新时间:2023-12-01 23:10:55 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What’s the best way to capitalise the first letter of each word in a string in SQL Server

(18 个回答)


8年前关闭。




我需要一个 SQL 语句来将每个单词的第一个字母大写。其他字符必须小写。

这些话可以是这样的:

wezembeek-oppem
roeselare
BRUGGE
louvain-la-neuve

必须是:
Wezembeek-Oppem
Roeselare
Brugge
Louvain-La-Neuve

这应该是一个UPDATE语句,我想更新一个列的数据。
非常感谢您提前回答,我是 SQL 新手。

最佳答案

您是要求重命名列本身还是将列内的数据大写?如果您必须更改其数据,请使用以下命令:

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])

关于SQL:仅大写第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15290754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com