我在Students表中有一个名字字段,它是一个以逗号分隔的字符串格式" LastName,FirstName,Middle Name"。在SQL查询中执行select语句时我需要将其分解为单独的字段我如何在SQL中实现这一目标?。有些时候中间的内容无法实现。
SUBSTRING(Name,CHARINDEX(',',Name,1)+2,LEN(Name)) AS FirstName,
SUBSTRING(Name,1,CHARINDEX(',',Name,1)-1) AS LastName,
如果没有中间名,上面的代码就可以正常工作。
答案 0 :(得分:1)
首先在字符串中找到逗号(,)的出现位置。然后使用CASE
表达式来获取逗号的数量。如果有2个逗号,那么我们可以假设中间名也在那里。如果1则只有名字和姓氏。然后使用LEFT
,RIGHT
,SUBSTRING
,CHARINDEX
字符串函数的组合。
<强>查询强>
select t.name,
left(
t.name,
charindex(',', t.name, 1) - 1
) last_name,
case t.comma_num
when 2
then substring(
t.name,
charindex(',', t.name, 1) + 1,
len(name) -
(charindex(',', t.name, 1) + 1) - charindex(',', reverse(t.name), 1) + 1
)
when 1
then right(
t.name,
charindex(',', reverse(t.name), 1) - 1
)
else null end as first_name,
case t.comma_num
when 2
then right(
t.name, charindex(',', reverse(t.name), 1) - 1
)
else null end as middle_name
from (
select name,
len(name) - len(replace(name, ',', '')) comma_num
from [your_table_name]
)t;
<强> Find demo here 强>
答案 1 :(得分:1)
这应该可以满足您的需求:
declare @tmp table (fullname varchar(100));
insert @tmp values('James, Billy, L'), ('John, Snow');
select
fullname
, [Last Name]
, case
when charindex(',', Remainder, 0) > 0
then ltrim(substring(Remainder, 0, charindex(',', Remainder, 0)))
else ltrim(Remainder)
end [First Name]
, case
when charindex(',', Remainder, 0) = 0
then NULL
else ltrim(substring(Remainder, charindex(',', Remainder, 0) + 1, len(Remainder)))
end [Middle Name]
from
(select
fullname
, substring(fullname, 0, charindex(',', fullname, 0)) [Last Name]
, substring(fullname, charindex(',', fullname, 0) + 1, len(fullname)) [Remainder]
from @tmp) result;
答案 2 :(得分:0)
Use CTE and SUBSTRING AND CHARINDEX funntions
DECLARE @Name VARCHAR(100) = 'James, Billy, L'
--DECLARE @Name VARCHAR(100) = 'James, '', L'
;WITH _CTE ( SplitedNames ,RemainStr) AS
(
SELECT SUBSTRING(@Name,0,CHARINDEX(',',@Name)),
SUBSTRING(@Name,CHARINDEX(',',@Name)+1,LEN(@Name))
UNION ALL
SELECT CASE WHEN CHARINDEX(',',RemainStr) = 0 THEN RemainStr ELSE
SUBSTRING(RemainStr,0,CHARINDEX(',',RemainStr)) END,
CASE WHEN CHARINDEX(',',RemainStr) = 0 THEN '' ELSE
SUBSTRING(RemainStr,CHARINDEX(',',RemainStr)+1,LEN(RemainStr))
END
FROM _CTE
WHERE RemainStr <> ''
)
SELECT SplitedNames FROM _CTE