How do I display the first letter as uppercase?

后端 未结 7 1346
孤城傲影
孤城傲影 2021-01-18 08:41

I have fname and lname in my database, and a name could be stored as JOHN DOE or john DOE or JoHN dOE, but ultimately I want to display it as John Doe

fname being Jo

7条回答
  •  鱼传尺愫
    2021-01-18 09:21

    For simple names, this will work. Beware of special cases (like "Ronald McDonald" in the below example).

    In SQL Server:

    SELECT  --step 2: combine broken parts into a final name
      NAME_PARTS.FNAME_INITIAL + NAME_PARTS.REST_OF_FNAME AS FNAME
     ,NAME_PARTS.LNAME_INITIAL + NAME_PARTS.REST_OF_LNAME AS LNAME
    FROM
      (     --step 1: break name into 1st letter and "everything else"
      SELECT
        UPPER(SUBSTRING(TEST.FNAME,1,1)) AS FNAME_INITIAL
       ,UPPER(SUBSTRING(TEST.LNAME,1,1)) AS LNAME_INITIAL
       ,LOWER(SUBSTRING(TEST.FNAME,2,LEN(TEST.FNAME))) AS REST_OF_FNAME
       ,LOWER(SUBSTRING(TEST.LNAME,2,LEN(TEST.LNAME))) AS REST_OF_LNAME
      FROM
        (   --step 0: generate some test data
              SELECT 'john' AS FNAME, 'doe' as LNAME
        UNION SELECT 'SUZY', 'SMITH'
        UNION SELECT 'bIlLy', 'BOb'
        UNION SELECT 'RoNALD', 'McDonald'
        UNION SELECT 'Edward', NULL
        UNION SELECT NULL, 'Jones'
        ) TEST
      ) NAME_PARTS
    

    In Oracle

    SELECT  --step 2: combine broken parts into a final name
      NAME_PARTS.FNAME_INITIAL || NAME_PARTS.REST_OF_FNAME AS FNAME
     ,NAME_PARTS.LNAME_INITIAL || NAME_PARTS.REST_OF_LNAME AS LNAME
    FROM
      (     --step 1: break name into 1st letter and "everything else"
      SELECT
        UPPER(SUBSTR(TEST.FNAME,1,1)) AS FNAME_INITIAL
       ,UPPER(SUBSTR(TEST.LNAME,1,1)) AS LNAME_INITIAL
       ,LOWER(SUBSTR(TEST.FNAME,2,LENGTH(TEST.FNAME))) AS REST_OF_FNAME
       ,LOWER(SUBSTR(TEST.LNAME,2,LENGTH(TEST.LNAME))) AS REST_OF_LNAME
      FROM
        (   --step 0: generate some test data
              SELECT 'john' AS FNAME, 'doe' as LNAME FROM DUAL
        UNION SELECT 'SUZY', 'SMITH' FROM DUAL
        UNION SELECT 'bIlLy', 'BOb' FROM DUAL
        UNION SELECT 'RoNALD', 'McDonald' FROM DUAL
        UNION SELECT 'Edward', NULL FROM DUAL
        UNION SELECT NULL, 'Jones' FROM DUAL
        ) TEST
      ) NAME_PARTS
    

提交回复
热议问题