将现有表格的每个单词都大写

时间:2019-10-21 02:52:05

标签: mysql sql

我有一张桌子叫做“艺术家”。 “艺术家”中有一个名为艺术家的列。

Artist
firstname lastname
Firstname lastname
Firstname Lastname
firstname

我尝试对此Post

进行查询

我想在“艺术家”表中大写每个艺术家的名字和姓氏的首字母。 期待:

Artist
Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname

我的某些艺术家没有名字,并且查询在开头添加了一个额外的字符:

enter image description here

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是使用CASE表达式,当Artist有两个名称时从另一个问题中选择公式,而只有一个名称时将首字母大写:

SELECT 
    CASE WHEN Locate(' ', Artist) = 0 THEN 
         -- firstname only
         CONCAT(UPPER(SUBSTRING(Artist, 1, 1)), 
                LOWER(SUBSTRING(Artist, 2)))
    ELSE
         -- firstname and lastname
         CONCAT(UPPER(SUBSTRING(Artist, 1, 1)),
                LOWER(SUBSTRING(Artist, 2, Locate(' ', Artist)-1)),
                UPPER(SUBSTRING(Artist, Locate(' ', Artist)+1,1)),
                LOWER(SUBSTRING(Artist, Locate(' ', Artist)+2)))
    END AS Artist
FROM Artists

输出:

Artist
Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname Lastname
Firstname
Firstname

Demo on dbfiddle