November 28, 2012 at 1:12 pm
Would anyone know what would be wrong with this query?
I'm using it to change names in this format: Doe, John M. to three fields: John M Doe
thus stripping out the comma after the first name (if present) and the period after the middle initial if exists and is present:
SELECT LTRIM(SubString(CustomerName,1,ISNULL(Nullif(CHARINDEX(' ',CustomerName),0),1000))) As First_Name,
LTRIM(SUBSTRING(CustomerName,CharIndex(' ',CustomerName),
CASE WHEN (CHARINDEX(' ',CustomerName,CHARINDEX(' ',CustomerName)+1)-CHARINDEX(' ',CustomerName))<=0 then 0
else CHARINDEX(' ',CustomerName,CHARINDEX(' ',CustomerName)+1)-CHARINDEX(' ',CustomerName) end )) as Middle_Name,
LTRIM(SUBSTRING(CustomerName,ISNULL(Nullif(CHARINDEX(' ',CustomerName,Charindex(' ',CustomerName)+1),0),CHARINDEX(' ',CustomerName)),
CASE WHEN Charindex(' ',CustomerName)=0 then 0 else LEN(CustomerName) end)) as Last_Name From dbo.Data$
Go
November 28, 2012 at 1:25 pm
what if your data is not in that exact format?
/*
--Results
First_Name Middle_Name Last_Name
Doe, John M.
*/
With [data$] (CustomerName)
AS
(
SELECT 'Doe, John M.'
)
SELECT LTRIM(SubString(CustomerName,1,ISNULL(Nullif(CHARINDEX(' ',CustomerName),0),1000))) As First_Name,
LTRIM(SUBSTRING(CustomerName,CharIndex(' ',CustomerName),
CASE WHEN (CHARINDEX(' ',CustomerName,CHARINDEX(' ',CustomerName)+1)-CHARINDEX(' ',CustomerName))<=0 then 0
else CHARINDEX(' ',CustomerName,CHARINDEX(' ',CustomerName)+1)-CHARINDEX(' ',CustomerName) end )) as Middle_Name,
LTRIM(SUBSTRING(CustomerName,ISNULL(Nullif(CHARINDEX(' ',CustomerName,Charindex(' ',CustomerName)+1),0),CHARINDEX(' ',CustomerName)),
CASE WHEN Charindex(' ',CustomerName)=0 then 0 else LEN(CustomerName) end)) as Last_Name From Data$
Lowell
November 28, 2012 at 1:38 pm
I've only found 5 out of 8,000 records which I simply hand scrubbed... all else were in stated format
November 28, 2012 at 2:11 pm
I can go with changing the first part to "SELECT LTRIM(SubString(CustomerName,-1" and that does the trick in this case
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply