SQL用下划线分隔名字

时间:2019-06-17 22:48:35

标签: sql sql-server tsql

当名称中带有下划线时,我试图将名字从中间名或中间名缩写中分离出来。当有空格时,我能够将名字从中间名中分离出来,但是下划线有麻烦。

如果可能的话,我希望将所有内容放在一起。

    SELECT 
[first name]
,  SUBSTRING([first name], 1,
                  CASE WHEN SUBSTRING(REVERSE([first name]), 2, 1) = ' '
                       THEN CHARINDEX(' ', [first name]) - 1
                       ELSE LEN([first name])
                  END) AS FirstName ,
        CASE WHEN SUBSTRING(REVERSE([first name]), 2, 1) = ' '
             THEN SUBSTRING([first name], LEN([first name]), 1)
             ELSE NULL
        END AS MiddleName
,   [Last Name]

FROM nametable

enter image description here

3 个答案:

答案 0 :(得分:3)

内联添加REPLACE函数:

 SELECT 
    [first name]
    ,  SUBSTRING([first name], 1,
                      CASE WHEN SUBSTRING(REVERSE(REPLACE([first name], '_', ' ')), 2, 1) = ' '
                           THEN CHARINDEX(' ', REPLACE([first name], '_', ' ')) - 1
                           ELSE LEN([first name])
                      END) AS FirstName ,
            CASE WHEN SUBSTRING(REVERSE(REPLACE([first name], '_', ' ')), 2, 1) = ' '
                 THEN SUBSTRING(REPLACE([first name], '_', ' '), LEN([first name]), 1)
                 ELSE NULL
            END AS MiddleName
    ,   [Last Name]

    FROM nametable

答案 1 :(得分:3)

以下示例使用两个case 表达式将一列分成两部分。它利用Substring的功能:如果指定的长度超过输入字符串的长度,则不会引发错误。

请注意,示例数据不是数据的图像,而是有用的数据。

declare @Samples as Table ( Name VarChar(20) );

insert into @Samples ( Name ) values
  ( 'Billy' ), ( 'Billy Bob' ), ( 'Billy_Joe' ), ( 'Edgar_7' ),
  ( '_' ), ( 'X_' ), ( '_Y' ), ( '' );

select Name,
  case
    when CharIndex( '_', Name ) > 0 then Left( Name, CharIndex( '_', Name ) - 1 )
    else Name end as FirstName,
  case
    when CharIndex( '_', Name ) > 0 then Substring( Name, CharIndex( '_', Name ) + 1, 20 )
    else NULL end as MiddleName
  from @Samples;

答案 2 :(得分:0)

感谢@HABO提供的数据示例,您也可以尝试以下方法:

SELECT L.Name,
       L.FirstName,
       CASE L.MiddleName WHEN '' THEN NULL ELSE L.MiddleName END AS MiddleName
FROM
(
    SELECT P.Name,
           REPLACE(SUBSTRING(P.UnderscoredName, 1, P.UnderscoreIndex), '_', '') AS FirstName,
           REPLACE(SUBSTRING(P.UnderscoredName, P.UnderscoreIndex, LEN(P.UnderscoredName) - P.UnderscoreIndex + 1),'_','') AS MiddleName
    FROM
    (
        SELECT K.Name,
               K.UnderscoredName,
               CHARINDEX('_', K.UnderscoredName) AS UnderscoreIndex
        FROM
        (
            SELECT Name,
                   REPLACE(CASE WHEN Name LIKE N'%[_]%' THEN Name ELSE Name + '_' END,' ','_') AS UnderscoredName
            FROM @Samples
        ) AS K
    ) AS P
) AS L;