如何从SQL中的给定字符串中提取子字符串

时间:2017-03-09 15:58:34

标签: sql sql-server-2012

我有全名,应该分为名字,姓氏和中间名。 以下是我的示例名称。

1. WILLEMS, JAN MARIE J
2. HLAVACEK, PATRICIA K
3. KLIMEK, CHRISTOPHER

现在我的名字,中间名和姓氏应该是

Firstname    Lastname    Middlename
JAN MARIE    WILLEMS       J
PATRICIA     HLAVACEK      K
CHRISTOPHER  KLIMEK

我尝试了以下查询。

            declare @FullName varchar(100)='KLIMEK, CHRISTOPHER'
Select  
    LTRIM(RTRIM(SUBSTRING(@FullName, 0, CHARINDEX(',', @FullName)))) As LastName
,SUBSTRING(@FullName,CHARINDEX(' ',LTRIM(RTRIM(@FullName)))+1,(LEN(LTRIM(RTRIM(@FullName)))-CHARINDEX(' ',LTRIM(RTRIM(@FullName)))-CHARINDEX(' ',REVERSE(LTRIM(RTRIM(@FullName))))))
,SUBSTRING( @FullName , LEN(LTRIM(RTRIM(@FullName))) -  CHARINDEX(' ',REVERSE(LTRIM(RTRIM(@FullName)))) + 2  , LEN(LTRIM(RTRIM(@FullName))))

如果没有中间名,则无法给出正确答案。

您能否提供您的意见?

1 个答案:

答案 0 :(得分:1)

提取部分名称可能会变得混乱,但这可能会满足您的需求:

select 
    Firstname  = left(rest,len(rest)-charindex(' ',reverse(rest)))
  , Lastname
  , Middlename = case 
      when charindex(' ',rest)>0 
        then right(rest,charindex(' ',reverse(rest))-1)
      else ''
      end
from (
  select
      Lastname = left(name, charindex(',',name+',')-1)
    , rest     = ltrim(rtrim(stuff(name, 1,charindex(',',name+','),'')))
  from t
  ) as s

rextester演示:http://rextester.com/UOMM64478

返回:

+-------------+----------+------------+
|  Firstname  | Lastname | Middlename |
+-------------+----------+------------+
| JAN MARIE   | WILLEMS  | J          |
| PATRICIA    | HLAVACEK | K          |
| CHRISTOPHER | KLIMEK   |            |
+-------------+----------+------------+

如果middlename应该只是一个中间的首字母,长度为1,这将适应:

select 
    Firstname  = case 
      when charindex(' ',reverse(rest))=2
        then left(rest,len(rest)-2)
      else rest
      end
  , Lastname
  , Middlename = case 
      when charindex(' ',reverse(rest))=2
        then right(rest,charindex(' ',reverse(rest))-1)
      else ''
      end
  , name
from (
  select
      Lastname = left(name, charindex(',',name+',')-1)
    , rest     = ltrim(rtrim(stuff(name, 1,charindex(',',name+','),'')))
    , name
  from t
  ) as s

返回:

+-------------+----------+------------+----------------------+
|  Firstname  | Lastname | Middlename |         name         |
+-------------+----------+------------+----------------------+
| JAN MARIE   | WILLEMS  | J          | WILLEMS, JAN MARIE J |
| PATRICIA    | HLAVACEK | K          | HLAVACEK, PATRICIA K |
| CHRISTOPHER | KLIMEK   |            | KLIMEK, CHRISTOPHER  |
| JAN MARIE   | WILLEMS  |            | WILLEMS, JAN MARIE   |
+-------------+----------+------------+----------------------+