我有一个查询,用于解析全名中的名字,中间名和姓氏。
DECLARE @name VARCHAR(20) = 'martin'
SELECT first_name = (
CASE LEN(REPLACE(UPPER(@name), ' ', ''))
WHEN LEN(UPPER(@name)) - 1
THEN PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 2)
ELSE PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 3)
END
)
,mi = (
CASE LEN(REPLACE(UPPER(@name), ' ', ''))
WHEN LEN(UPPER(@name)) - 1
THEN NULL
ELSE PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 2)
END
)
,last_name = (PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 1))
所以问题是,当同时输入名字和姓氏时,此查询可以正常工作。就像@name ='Martin Joe'一样。但是,当输入的是一个单一名称@name ='Martin'时,它将以姓氏开头,并以MI开头为null。
@name = 'Martin'
First name - Null
MI - Null
Last name - Martin
@name = 'Martin'
First name - Martin
MI - Null
Last name - Null
应该将名字显示为“ Martin,MI和姓氏显示为null”。有帮助吗?!
答案 0 :(得分:1)
听起来像您只希望查询顺序颠倒(名字和姓氏翻转),这对您有用吗?
DECLARE @name VARCHAR(20) = 'Martin Joe'
SELECT last_name = (
CASE LEN(REPLACE(UPPER(@name), ' ', ''))
WHEN LEN(UPPER(@name)) - 1
THEN PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 2)
ELSE PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 3)
END
)
,mi = (
CASE LEN(REPLACE(UPPER(@name), ' ', ''))
WHEN LEN(UPPER(@name)) - 1
THEN NULL
ELSE PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 2)
END
)
,first_name = (PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 1))
此输入
DECLARE @name VARCHAR(20) = 'Martin Joe'
会给(我猜乔在这种情况下应该是fname吗?)
lname mi fname
MARTIN NULL JOE
这个(现在是马丁在这种情况下的名字?)
DECLARE @name VARCHAR(20) = 'Martin'
会给:
lname mi fname
NULL NULL MARTIN
在旁注中,我使用了原始的SQL代码,并使用:http://poorsql.com/对其进行格式化,这很方便:)
答案 1 :(得分:0)
您的名字WHEN
中需要一个附加的CASE
来解决折叠后的字符串和原始字符串长度相同的问题,因此这种情况将被视为名字。然后,在last_name上必须有一个CASE
,以确保折叠后的字符串和原始字符串不的长度相同。
这似乎可行:
DECLARE @name VARCHAR(20) = 'martin'
SELECT first_name = (
CASE LEN(REPLACE(UPPER(@name), ' ', ''))
WHEN LEN(UPPER(@name)) - 1
THEN PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 2)
WHEN LEN(@name)
THEN PARSENAME('..' + UPPER(@name), 1)
ELSE PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 3)
END
)
,mi = (
CASE LEN(REPLACE(UPPER(@name), ' ', ''))
WHEN LEN(UPPER(@name)) - 1
THEN NULL
ELSE PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 2)
END
)
,last_name =
CASE
WHEN LEN(REPLACE(UPPER(@name), ' ', '')) < LEN(UPPER(@name))
THEN (PARSENAME(REPLACE(UPPER(@name), ' ', '.'), 1))
ELSE NULL
END