最近,当我必须将Fullname分成4个部分时,我遇到了这个问题。 Firstname, Middle name/Initial, Lastname and Suffix
。我很难过。请帮忙。
Declare @name varchar(100)
set @name = 'Michael John T. Mac Tavish, Jr.'
SELECT @name, substring(@name, 1,charindex(' ',@name)) as firstname,
left(ltrim(substring(@name, charindex(' ',@name),len(@name)-charindex(' ',@name)+1)),2) as MiddleName,
substring(@name, len(@name)-CHARINDEX(' ', REVERSE(@name))+1, len(@name)) as lastname
答案 0 :(得分:0)
尝试用下面的代码替换你的sql代码 -
Declare @name varchar(100)
set @name = 'Michael John T. Mac Tavish, Jr.'
SELECT @name as Name,
rtrim(ltrim(substring(@name,1,dbo.pos(@name,' ',2)))) as firstname,
rtrim(ltrim(substring(@name,dbo.pos(@name,' ',2)+1,charindex('.',@name)-dbo.pos(@name,' ',2)))) as MiddleName,
rtrim(ltrim(substring(@name,charindex('.',@name)+1,charindex(',',@name)-charindex('.',@name)-1))) as lastname,
rtrim(ltrim(substring(@name,charindex(',',@name)+1,len(@name)))) as Suffix
用于查找字符串中第n个字符出现的函数代码 -
CREATE FUNCTION dbo.Pos(@string VARCHAR(MAX),@delim VARCHAR(1),@occur INT)
RETURNS INT
AS
BEGIN
DECLARE @pos int, @counter int, @ret int
SET @pos = CHARINDEX(@delim, @string)
set @counter = 1
if @occur = 1 set @ret = @pos
else
begin
while (@counter < @occur)
begin
select @ret = CHARINDEX(@delim, @string, @pos + 1)
set @counter = @counter + 1
set @pos = @ret
end
end
RETURN @ret
END
但我真的建议你重新构建你的问题并提供更多信息(你的字符串模式,如何识别分隔符以提取名称部分等等)以更有效地解决问题。