The answer partly depends: if this example is your exact question, it's short enough to do in a somewhat simple way (keeping in mind 100 percent accuracy will never be possible for names or addresses). Split functions convert strings into relational
data, which although technically superior, is overkill, you want to split into multiple columns, not into a relational model (in this case).
If it's a more general question on a situation with lots more virtual columns, including names and addresses, then it's harder, because there is no way to absolutely and completely deal with double first names, hyphenated last names, and last names like
"de la cruz".
Here's one of about a million ways to do it. I like using APPLY, because it makes code cleaner, and particularly with string functions, helps you avoid calling string functions repeatedly, or nesting one inside another over and over. My example
dodged the firstname/lastname topic, but you could use the same basic method to imperfectly split on the first space in the name area.
Declare @ExampleData Table (Instr Varchar(999))
Insert @ExampleData
Select * From ( Values
('BLR Siratsiuk Illia 09/04/1994 10.54 10.66')
, ('ESP Rodrguez ngel David 25/04/1980 10.14 10.32')
, ('USA De La Hoya Jean David 30/11/1979 10.22 10.23')
) as VT(VV)
Select Substring(Instr, 1, NameStart - 1) as Countr
, Substring(Instr, NameStart, DOBStart - NameStart) as Name
, Substring(Instr, DOBStart + 1, 10) as DOB
, Substring(Instr, PBStart, SBStart + 1 - PBStart) as PB
, Substring(Instr, SBStart + 1, 5) as SB
, CA_001.*, ED.*
From @Exampledata ED
Cross apply (Select Charindex(' ', Instr) + 1 as NameStart
, patindex('% [0-9][0-9][//]%', Instr) as DOBStart
, patindex('% [0-9][0-9][.]%', Instr) as PBStart
, len(Instr) - 5 as SBStart
) as CA_001
Results:
Countr Name DOB PB SB
BLR Siratsiuk Illia 09/04/1994 10.54 10.66
ESP Rodrguez ngel David 25/04/1980 10.14 10.32
USA De La Hoya Jean David 30/11/1979 10.22 10.23
At times, reversing the string adds some additional ways to deal with the data. I bet someone will post an answer that uses reverse as part of the solution.
-
Edited by
johnqflorida
Friday, June 19, 2015 12:56 PM
Fixed typo