I have a list of customer whose name is given as a full name. I want to create a function that takes the full name as parameter and returns the first and last name separately. If this is not possible I can have two separate functions one that returns the first name and the other that returns the last name. The full name list contains names that have a maximum of three words. What I want is this:-
- When a full name is composed of two words. The first one should be the name and the second one should be the last name.
- When a full name is composed of three words. The first and middle words should be the first name while the third word should be the last name.
Example:-
**Full Name**
John Paul White
Peter Smith
Ann Marie Brown
Jack Black
Sam Olaf Turner
Result:-
**First Name Last Name**
John Paul White
Peter Smith
Ann Marie Brown
Jack Black
Sam Olaf Turner
I have search and found solutions that are not working as intended and would like some advice.
8条答案
按热度按时间wgx48brx1#
Keeping it short and simple
Result:
ttygqcqt2#
If you are certain that your names will only ever be two or three words, with single spaces, then we can rely on the base string functions to extract the first and last name components.
Yuck, but it seems to work. My feeling is that you should fix your data model at some point. A more ideal place to scrub your name data would be outside the database, e.g. in Java. Or, better yet, fix the source of your data such that you record proper first and last names from the very beginning.
Demo here:
Rextester
qzlgjiam3#
Another option (just for fun) is to use a little XML in concert with an CROSS APPLY
Example
Returns
fsi0uk1n4#
You're trying to do two things at once...I won't solve for you, but here's the direction I'd take:
Check this out for string splitting: https://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql.html . This will allow you to parse the name into a temp table and you can perform your logic on it to create names based on your rules
Create this as a table-valued function so that you can return a single row of parsed FirstName, LastName from your parameter. That way you can join to it and include in your results
ou6hu8tu5#
Have you tried by Using PARSENAME Function?
The last method in splitting a full name into its corresponding first name and last name is the use of the PARSENAME string function, as can be seen from the following script:
For more information, Goto this Site
This is the output..
flseospp6#
Make it a table-valued function.
see here for an example
And this is the code you need to create your function. Basically you just need to split your LastName
You can run as
SELECT * FROM dbo.ufnParseName('M J K');
Why Table-Valued-Function
You can get rid off the duplication of your sql query and achieve DRY
ufj5ltwl7#
You can try the below query. It is written as per your requirement and it only handles full_name with 2 or 3 parts in it.
tkqqtvp18#
What worked for me was the following: