T-SQL Query Problem - sql

I have a column in Database called Full Name and I want split that name as FirstName and LastName:
Here is an Example:
FullName
Sam Peter
I want this to be
FirstName LastName
--------------------
Sam Peter
But the Problem is Some of the columns in Database have Full Names Like this
FullName
--------
Sam George Jack Peter
Sam Adam Peter
I want this to be
FirstName LastName
--------- --------
Sam George Jack Peter
Sam Adam Peter
How do I write T-SQL Query for this.
Thanks in Advance for all the help

There's a very thorough name parsing routine described in this answer. It handles your situation, along with much trickier cases like "Mr. Martin J Van Buren III".

String manipulation in SQL Server is notoriously weak.
Your best bet is to do it in your application layer.
For your example with more than 2 names, how do you know which fields those additional names go into? Are you guaranteed they will always have only one last name?

Found this on net (did not test it)
REVERSE(SUBSTRING(REVERSE([FullName]),1,FINDSTRING(REVERSE([FullName])," ",1)))
You can test it with
SELECT REVERSE(SUBSTRING(REVERSE([FullName]),1,FINDSTRING(REVERSE([FullName])," ",1)))
FROM Table
if it works you can then
UPDATE Table
SET LastName = REVERSE(SUBSTRING(REVERSE([FullName]),1,FINDSTRING(REVERSE([FullName])," ",1)))
I leave the exercise for the first name to you.

Are you just splitting at the last space? If so this should work:
select 'Sam George Jack Peter' as FullName
into #names
union select 'Sam Adam Peter'
select LEFT(FullName,LEN(FullName)-CHARINDEX(' ',REVERSE(FullName))) as FirstName
,RIGHT(FullName,CHARINDEX(' ',REVERSE(FullName))-1) as LastName
from #names
EDIT:
To handle names with no spaces and put the FullName as LastName
select 'Sam George Jack Peter' as FullName
into #names
union select 'Sam Adam Peter'
union select 'Peter'
select CASE
WHEN CHARINDEX(' ',FullName) = 0 THEN ''
ELSE LEFT(FullName,LEN(FullName)-CHARINDEX(' ',REVERSE(FullName)))
END as FirstName
,CASE
WHEN CHARINDEX(' ',FullName) = 0 THEN FullName
ELSE LTRIM(RIGHT(FullName,CHARINDEX(' ',REVERSE(FullName))))
END as LastName
from #names

Related

Extract the first word before a space using SQL

Let's say I have a column in my users table called name:
name
----
Brian
Jill Johnson
Sarah
Steven Smith
I want to write a PostgreSQL query to fetch just the first name. This is what I have so far:
select substr(name, 0, position(' ' IN name) | length(name) + 1) as first_name from users;
name
----
Brian
Jill
Sarah
Steven
This appears to work but I feel like there much be an easier way.
Although I don't follow the logic, your code looks like Postgres. If so, use split_part():
select split_part(name, ' ', 1)
from users;

Split Name into Last name, First Name, Middle Name in SQL

I have a record below. I want to split the name into Lname, Fname, Mname
Name
John, David Handsome
Here is my query. I was able to get Lname but not Fname and Mname yet.
SELECT
NAME,
LEFT(NAME,CHARINDEX(',',NAME)-1) AS LNAME
FROM TABLE
My desired output would be:
Name Lname Fname Mname
John, David Handsome John Daivd Handsome
If the format of name is gonna remain the same then use below :
select name,LEFT(NAME,CHARINDEX(',',NAME)-1) AS LNAME, regexp_substr(name,'[^ ]+',1,2) as fname,regexp_substr(name,'[^ ]+',1,3) mname from table;
You can do it like this;
SELECT
LEFT(NAME,CHARINDEX(',',NAME)-1) AS LNAME,
LEFT(REPLACE(NAME,LEFT(NAME,CHARINDEX(',',NAME)+1),''),CHARINDEX(' ',REPLACE(NAME,LEFT(NAME,CHARINDEX(',',NAME)+1),''))-1) AS FNAME,
REPLACE(REPLACE(NAME,LEFT(NAME,CHARINDEX(',',NAME)+1),''),LEFT(REPLACE(NAME,LEFT(NAME,CHARINDEX(',',NAME)+1),''),CHARINDEX(' ',REPLACE(NAME,LEFT(NAME,CHARINDEX(',',NAME)+1),''))-1),'') AS MNAME
It comes little confusing because of nested replace and charindex functions. But if you focus on them closely, logic is quite simple.

UPDATING a column to take first letter from another column

I would like to UPDATE my table to replace / insert in the INITIALS column, the first letter in the first name column
Table name: Mano
Title Firstname Lastname Telephone Initial Gender More columns
1 Mr Adam Smith 001
2 Mrs Angela Evans 002 AE
3 Mr Bill Towny 003
4 Miss Dame Beaut 004
I am interested in transforming it as per below
Title Firstname Lastname Telephone Inital Gender More columns
1 Mr Adam Smith 001 A
2 Mrs Angela Evans 002 A
3 Mr Bill Towny 003 B
4 Miss Dame Beaut 004 D
Many thanks
This seems like a simple update:
update t
set initials = left(firstname, 1);
I should point out that you don't even need a column. You can declare this as a computed column:
alter t add initials as (left(firstname, 1));
This would provide a column called initials (assuming that name is not already used) that always has the first letter of the firstname column -- without an update.
You can use substring function,
SELECT SUBSTR(Firstname, 1, 1) from mango;
Hope using this select statement you can update the table.
If you need the update query, let me know will give you
Left is the best and would more better if we use this with TRIM to prevent the extra spaces if any:
UPDATE TABLE table1 SET Initial = LEFT(LTRIM(Firstname), 1)
Add a computed column, will never be inconsistent:
alter table Mano add Initial as SUBSTR(Firstname, 1, 1)

How do you split data from one column into two?

I just recently started learning about SQL in MS Access and SQL Server so I have very limited knowledge, but what I'm looking for is help with a query in MS Access.
I know how to merge 2 columns into 1 and have the final result separated by a comma or whatever symbol I'd like. But, how do I do the opposite?
In my case, I have a column (LastFirstName) in my table (MEMBERS) where the data would look something like this: "Smith, Middle John" etc.
What I'm having trouble with is figuring out how to permanently separate the data into 2 separate columns within the same table (LastName and FirstName) and not just using a query to display them like that.
Any help would be greatly appreciated, thanks!
Starting with
memberID LastFirstName LastName FirstName
-------- ------------- -------- ---------
1 Doe, John
the query
UPDATE Members SET
LastName = Trim(Left(LastFirstName, InStr(LastFirstName, ",") - 1)),
FirstName = Trim(Mid(LastFirstName, InStr(LastFirstName, ",") + 1))
will result in
memberID LastFirstName LastName FirstName
-------- ------------- -------- ---------
1 Doe, John Doe John

SQL: How to find exact matches of words within a text

Please bear with me, I'm new to Access and SQL.
What I'm trying to do is to write a SQL query to filter through two tables - one contains words that are split into two columns and the other contains text. Essentially, what I want is a new table that gives me all of the exact matches of the two columns of words with the column of text.
Here's an analogous database to simulate what I want as a result:
Table A:
FirstName: LastName:
John Doe
Jane Doe
Josh Smith
James Jones
David Johnson
Table B:
FullName:
Jake Davidson
Mike Peters
Jason James
John Michael Smith
Query Result:
FirstName: LastName: FullName:
John Doe John Michael Smith
Josh Smith John Michael Smith
James Jones Jason James
(notice that the David - Davidson match didn't come up. i.e. I'd like exact matches only)
So help me fill in the blanks:
SELECT TableA.FirstName,TableA.LastName, TableB.FullName
FROM TableA,TableB
WHERE TableB.FullName LIKE (has an exact match with TableA.FirstName--not sure what to put )
UNION
SELECT TableA.FirstName,TableA.LastName, TableB.FullName
FROM TableA,TableB
WHERE TableB.FullName LIKE (has an exact match with TableA.LastName--not sure what to put)
;
This will be dependant on what you want it to do with FullNames with more than two names, like "John Jacob Smith", but, assuming you want it to ignore the middle word[s],
then try
Select firstname, lastname, fullname
from tableA a
Join tableb f
On f.firstname = Mid(a.fullname, 1, InStr(a.fullname, " ")-1)
Join tableb l
On l.lastname = Mid(a.fullname, InStrRev(a.FullNamee, " ")+1)
Here is an approach that compares each FullName to both Firstname and LastName:
select a.Firstname, a.LastName, b.FullName
from tableA as a inner join
tableB as b
on instr(' '&b.FullName&' ', ' '&a.FirstName&' ') > 0 and
instr(' '&b.FullName&' ', ' '&a.Lastname&' ') > 0
It assume that the delimiter for names is a space (as in your example). The comparison attaches a space onto the beginning and end of FullName and then looks for a space-padded first name and last name.