I need to break out the name field to show last name and first initial in separate fields.
So far, I can break out the LastName, FirstName, but is there a way I can only select the first name initial?
regexp_substr(name, '[^,]+', 1, 1) as LastName,
regexp_substr(name, '[^,]+', 1, 2) as FirstName
I'm confused didn't see "oracle" tag. So these code snippets will only work with SQL Server:
You can do this by using standard string functions.
DECLARE #name VARCHAR(100);
SELECT #name = 'Tom Sheldon'
-- you can use this instead of regular expressions
SELECT RIGHT(#name, CHARINDEX(' ', #name)+3) + ' ' + LEFT(#name, 1) + '.' AS name
Returns:
name
Sheldon T.
and
DECLARE #name VARCHAR(100);
SELECT #name = 'Tom Sheldon'
-- you can use this instead of regular expressions
SELECT
RIGHT(#name, CHARINDEX(' ', #name)+3) AS LastName,
LEFT(#name, 1) AS FirstName
Returns:
LastName
FirstName
Sheldon
T
you can use SUBSTR with the resuklt of the regexp_substr
with rws as (
select 'lastname,firstname' str from dual
)
SELECT regexp_substr(str, '[^,]+', 1, 1) as LastName,
SUBSTR(regexp_substr(str, '[^,]+', 1, 2),1,1) as FirstNameinitial
from rws
LASTNAME | FIRSTNAMEINITIAL
:------- | :---------------
lastname | f
db<>fiddle here
Hah!
This might be inelegant, but it worked:
substr ( (regexp_substr(name, '[^,]+', 1, 2)),2,1 ) as FirstName
I started the substring at 2, b/c there was a space between the comma and the first name. I now have two columns: LastName, FirstInit
Assuming that the separator is a comma, and using old-school INSTR() and SUBSTR(), this version will allow for the possibility that there may be zero or more spaces following the comma:
WITH nrow AS (
SELECT 'Lastname, Firstname' AS pers_name
FROM dual
)
SELECT SUBSTR (pers_name, 1, INSTR (pers_name, ',') - 1) AS last_name,
SUBSTR (LTRIM (SUBSTR (pers_name, INSTR (pers_name, ',') + 1)), 1, 1) AS first_init
FROM nrow
/
Related
I try to get first name, last name, provider from an email address "ben.ghol#gmail.com" but it doesn't work.
Table emailtable.
My code here:
select
SUBSTR(email,1, INSTR(email,'.')-1) as firstname,
SUBSTR(email,INSTR(email,'.')+1, INSTR(email,'#')-1) as lastname,
SUBSTR(email,INSTR(email,'#')+1,INSTR(email,'.')-1) as "provider"
from emailtable;
The third argument for SUBSTR is the length of the substring (and not the position of the end character).
You can use a nested sub-query to find the position of the separators and then use those values in SUBSTR in the outer query:
SELECT SUBSTR(email, 1, name_separator - 1) AS first_name,
SUBSTR(email, name_separator + 1, at_separator - name_separator - 1)
AS last_name,
SUBSTR(email, at_separator + 1, domain_separator - at_separator - 1)
AS domain
FROM (
SELECT email,
INSTR(email, '.') AS name_separator,
INSTR(email, '#') AS at_separator,
INSTR(email, '.', INSTR(email, '#')) AS domain_separator
FROM emailtable
)
Which, for the sample data:
CREATE TABLE emailtable ( email ) AS
SELECT 'ben.ghol#gmail.com' FROM DUAL;
Outputs:
FIRST_NAME
LAST_NAME
DOMAIN
ben
ghol
gmail
db<>fiddle here
You can use regexp_substr():
select regexp_substr(email, '^[^.]+') as firstname,
regexp_substr(email, '[^.#]+', 1, 2) as lastname,
regexp_+substr(email, '[^#]+$') as provider
from (select 'ben.ghol#gmail.com' as email from dual) x;
Here is a db<>fiddle.
SUBSTR takes 3 parameters: input string, start position and length of substring.
You appear to be using end position as the 3rd parameter.
You can get the length to use as the 3rd parameter by doing (end position - start position + 1)
Wasn't sure of the best way to word this. So I have a column with names, as below:
SalesPerson_Name
----------------
Undefined - 0
Sam Brett-sbrett
Kelly Roberts-kroberts
Michael Paramore-mparamore
Alivia Lawler-alawler
Ryan Hooker-rhooker
Heather Alford-halford
Cassandra Blegen-cblegen
JD Holland-jholland
Vendor Accounts-VENDOR
Other Accounts-OTHER
Getting the names separated is easy enough with PARSENAME and REPLACE functions, but where I'm running into a pickle is with getting rid of the 'junk' at the end:
SELECT SalesPerson_Key
,SalesPerson_Name
,CASE
WHEN PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 2) IS NULL
THEN PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 1)
ELSE PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 2)
END AS FirstName
,CASE
WHEN PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 2) IS NULL
THEN NULL
ELSE PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 1)
END AS LastName
FROM Salesperson
RESULTS FOR LASTNAME COLUMN:
LastName
--------
0
Brett-sbrett
Roberts-kroberts
Paramore-mparamore
Lawler-alawler
Hooker-rhooker
Alford-halford
Blegen-cblegen
Holland-jholland
Accounts-VENDOR
Accounts-OTHER
Specifically, I want to get rid of the text (userid) at the end of the last name. If the names were the same length, I could just use a RIGHT function, but they vary in length. Ideas?
select left(PARSENAME(REPLACE(SalesPerson_Name, ' ', '.'), 1), len(SalesPerson_Name)-CHARINDEX('-',SalesPerson_Name)-1)
You are getting charindex of - and taking the left string of it.
If you just want to remove the last word (username) you can use a query like this
select
rtrim(
substring(
SalesPerson_Name,
1,
charindex('-',SalesPerson_Name,1)-1
)
)
from Salesperson
The charindex function locates the occurrence of the character/s you are looking for.
Consider whether hyphen is followed by a space or not, and split depending on these two cases
with Salesperson( SalesPerson_Name ) as
(
select 'Undefined - 0' union all
select 'Sam Brett-sbrett' union all
select 'Kelly Roberts-kroberts' union all
select 'Michael Paramore-mparamore' union all
select 'Alivia Lawler-alawler'
)
select case when substring(SalesPerson_Name,charindex(' ',SalesPerson_Name)+1,1) = '-' then
substring(SalesPerson_Name,charindex(' ',SalesPerson_Name)+3,len(SalesPerson_Name))
else
substring(SalesPerson_Name,charindex(' ',SalesPerson_Name)+1,len(SalesPerson_Name))
end as last_name
from Salesperson s;
last_name
------------------
0
Brett-sbrett
Roberts-kroberts
Paramore-mparamore
Lawler-alawler
SELECT TOP 1 REPLACE(name, , '' )
FROM OBJ_R) AS lastname
And
SELECT SUBSTRING(NAME
FROM 1 FOR POSITION(',' IN NAME)-1)
FROM OBJ_R
instead of
Beyeler,Nicole Nicole
Müller, Barbara Barbara
Ostmann,Heinz Heinz
I tried this one:
SELECT SUBSTRING(NAME
FROM 1 FOR POSITION(',' IN NAME)-1)
FROM OBJ_R
One option uses CHARINDEX with SUBSTRING:
SELECT
name,
LTRIM(SUBSTRING(name,
CHARINDEX(',', name) + 1,
LEN(name) - CHARINDEX(',', name))) AS first_name
FROM OBJ_R;
Demo
Note: I use LTRIM above because your sample data implies that there might be whitespace after the comma, after the last name. If not, then you may remove it.
I am trying to get First name from employee table, in employee table full_name is like this: Dow, Mike P.
I tried with to get first name using below syntax but it comes with Middle initial - how to remove middle initial from first name if any. because not all name contain middle initial value.
-- query--
select Employee_First_Name as full_name,
SUBSTRING(
Employee_First_Name,
CHARINDEX(',', Employee_First_Name) + 1,
len(Employee_First_Name)) AS FirstName
---> remove middle initial from right side from employee
-- result
Full_name Firstname Dow,Mike P. Mike P.
--few example for Full_name data---
smith,joe j. --->joe (need result as)
smith,alan ---->alan (need result as)
Instead of specifying the len you need to use charindex again, but specify that you want the second occurrence of a space.
select Employee_First_Name as full_name,
SUBSTRING(
Employee_First_Name,
CHARINDEX(',', Employee_First_Name) + 1,
CHARINDEX(' ', Employee_First_Name, 2)) AS FirstName
One thing to note, the second charindex can return 0 if there is no second occurence. In that case, you would want to use something like the following:
select Employee_First_Name as full_name,
SUBSTRING(
Employee_First_Name,
CHARINDEX(',', Employee_First_Name) + 1,
IIF(CHARINDEX(' ', Employee_First_Name, 2) = 0, Len(Employee_First_name), CHARINDEX(' ', Employee_First_Name, 2))) AS FirstName
This removes the portion before the comma.. then uses that string and removes everything after space.
WITH cte AS (
SELECT *
FROM (VALUES('smith,joe j.'),('smith,alan'),('joe smith')) t(fullname)
)
SELECT
SUBSTRING(
LTRIM(SUBSTRING(fullname,CHARINDEX(',',fullname) + 1,LEN(fullname))),
0,
COALESCE(NULLIF(CHARINDEX(' ',LTRIM(SUBSTRING(fullname,CHARINDEX(',',fullname) + 1,LEN(fullname)))),0),LEN(fullname)))
FROM cte
output
------
joe
alan
joe
To be honest, this is most easily expressed using multiple levels of logic. One way is using outer apply:
select ttt.firstname
from t outer apply
(select substring(t.full_name, charindex(', ', t.full_name) + 2, len(t.full_name) as firstmi
) tt outer apply
(select (case when tt.firstmi like '% %'
then left(tt.firstmi, charindex(' ', tt.firstmi)
else tt.firstmi
end) as firstname
) as ttt
If you want to put this all in one complicated statement, I would suggest a computed column:
alter table t
add firstname as (stuff((case when full_name like '%, % %.',
then left(full_name,
charindex(' ', full_name, charindex(', ', full_name) + 2)
)
else full_name
end),
1,
charindex(', ', full_name) + 2,
'')
If format of this full_name field is the same for all rows, you may utilize power of SQL FTS word breaker for this task:
SELECT N'Dow, Mike P.' AS full_name INTO #t
SELECT display_term FROM #t
CROSS APPLY sys.dm_fts_parser(N'"' + full_name + N'"', 1033, NULL, 1) p
WHERE occurrence = 2
DROP TABLE #t
I am able to extract the first word from a string, using ANSI SQL, like this:
SELECT SUBSTRING(name FROM 1 FOR POSITION(' ' IN name)) AS first_name
However, if the original string is only one word long (ie, if there is no space), it returns an empty substring.
How can the above query be adapted to solve this problem?
Thanks in advance.
I'm sure there is a cleaner way to do it, but this works.
DECLARE #tbl TABLE (i varchar(100));
INSERT INTO #tbl ( i )
VALUES ('hello'), ('hello space here');
SELECT *,
SUBSTRING(i, 0, CASE CHARINDEX(' ', i)
WHEN 0 THEN LEN(i) + 1
ELSE CHARINDEX(' ', i)
END)
FROM #tbl
Simply but messy solution - add a space on the end:
SELECT SUBSTRING((name || ' ') FROM 1 FOR POSITION(' ' IN (name || ' '))) AS first_name
Use a conditional if statement.
For a MySQL/SQL Server answer:
SELECT IF(INSTR(name, ' ') >0, LEFT(name, INSTR(name, ' ') - 1), name) AS firstname
For Oracle:
SELECT IF(INSTRB(name, ' ', 1, 1) >0, SUBSTR(name, 1, INSTRB(name, ' ', 1, 1) - 1), name) AS firstname
I personally prefer the Regexp query for this, but below query also works.
You basically append a space at the end of the string and search for the position of the space using INSTR.
ORACLE:
select substr(Var1, 0,INSTR(Var1||' ',' ')) from table-name;
Replace Var1 with the column-name or string you are evaluating.
Put Column Name in place of #foo
DECLARE #Foo VARCHAR(50) = 'One Two Three'
SELECT
CASE
--For One Word
WHEN CHARINDEX(' ', #Foo, 1) = 0 THEN #Foo
--For multi word
ELSE SUBSTRING(#Foo, 1, CHARINDEX(' ', #Foo, 1) - 1)
END
DECLARE #test VARCHAR(50) = 'One Two Three'
SELECT SUBSTRING(LTRIM(#test),1,(CHARINDEX(' ',LTRIM(#test) + ' ')-1))
you can use this to get the first word of a string.initcap
will get you the first letter capital.
SELECT SUBSTR(column_1, 1, INSTR(column_1, ' ', 1,1) ) FROM table_name WHERE column_1= initcap('your string');