0
我試圖將全名分解爲最後一個,第一個,中間和後綴。我搜索,但無法找到與我的完全相同的格式。我有以下代碼,但運行完整選擇時出現此錯誤。sql將全名解析爲第一個,中間,最後和後綴
Msg 537, Level 16, State 3, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
SpaceComma表獲得正確的索引。 這是我有名字的格式:
CREATE TABLE #myfullnames (fullName VARCHAR(50))
GO
INSERT #myfullnames VALUES ('BROOK SR, JAMES P.')
INSERT #myfullnames VALUES ('BLOCK JR., BILL V.')
INSERT #myfullnames VALUES ('MOOR, CLODE M.')
INSERT #myfullnames VALUES ('SOUDER III, Laurence R.')
INSERT #myfullnames VALUES ('SOUDER, WILL')
INSERT #myfullnames VALUES ('KOLIV, Kevin E.')
INSERT #myfullnames VALUES ('Simk, JR. Thomas Todd')
INSERT #myfullnames VALUES ('Polio, Gary R.')
我會感謝你的幫助。謝謝。
select SplitNames.LastName, SplitNames.FirstName,
SplitNames.MiddleName, SplitNames.Title
from (
select [fullName]
, substring([fullName], 1, SpceTitle-1) as LastName
, substring([fullName], SpceMid,(SpceMid - SpceFirstName - 1)) as FirstName
, substring([fullName], SpaceComma.SpceTitle, (SpaceComma.SpceFirstName -
SpaceComma.SpceTitle)) as Title
, nullif(substring([fullName],SpaceComma.SpceMid+1,100),'') as
MiddleName
from (
select [fullName],
charindex(',',[fullName]) as Comma,
charindex(' ',[fullName]+space(1),charindex(',',[fullName])) as
SpceFirstName,
(len([fullName]) + 1 - charindex(' ',reverse([fullName]), 0)) as
SpceMid,
charindex(' ',[fullName], charindex (' ',reverse([fullName]))) as SpceTitle
from #myfullnames
) SpaceComma
) SplitNames
DROP TABLE #myfullnames