How can I split name in SQL - sql

I have a column in my table with 1000 names. I want to make a new column by splitting the name in new format: Example:
Santosh Kumar Yadav
It should be:
Santosh K Yadav
Middle name with only initials and rest name should be the same.
How can I do it ?

If all you want to do is replace second name with Initial. Here's an idea for MySQL database.
Assuming the name of names column is name & new column where you want to put data is formatted_name. You could try this.
UPDATE Users
SET formatted_name = REPLACE(
name,
SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1),
LEFT(SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1), 1)
);
Here's the demo
http://sqlfiddle.com/#!9/4e5f95

Following solution in Java
// get name from database and store in var1
String[] nameType = var1.split (' ');
// divide var1 into firstname middlename lastname by splitting name with 'space'
var1 = nameType [0] + ' ' + nameType [1].substring (0, 1) + ' ' + nameType [2];
// combine name types, but only first letter of middle name
// write var1 in database

Please try to make use of the below code. Its working fine in SQL Server 2012.
Note : This will work only for name with 3 parts.
DECLARE #Table TABLE (Name Varchar(100))
INSERT INTO #Table
(Name)
VALUES
('Santhosh Kumar Yadav'),
('John Thomas Mathew'),
('Thomas Mathew John'),
('Mathew John Thomas'),
('John Mathew Thomas')
SELECT
SUBSTRING(Name,1,CHARINDEX(' ',Name)+1) +
REVERSE(SUBSTRING(REVERSE(Name),1,CHARINDEX(' ',REVERSE(Name)))) AS Name
FROM
#Table

The OP didn't mention the db vendor. The sample version for Oracle:
with mynames (name) as
(select 'Santosh Kumar Yadav' from dual
union all
select 'Abc Defgh' from dual)
select
case when length(name) - length(replace(name, ' ', '')) + 1 < 3 then
name
else
regexp_replace(name,'(^| )([^ ])([^ ])*',' \2',2, 1)
end
from mynames
It replaces only second word in the string when string has more than 2 words.

For this result like
'Santosh Kumar Yadav' into 'Santosh K Yadav'
. You should create a function that convert
from 'Santosh Kumar Yadav' into 'Santosh K Yadav'
create function FullNameToShort(#name varchar(100))
returns varchar(100)
begin
declare #input varchar(100)
set #input=#name
declare #i int
declare #output varchar(100)
declare #ch varchar
declare #lname varchar(25)
declare #flag int
set #flag=0
set #i=1
while #i<=LEN(#input)
begin
if(SUBSTRING(#input,#i,1)=' ')
begin
set #lname=(SUBSTRING(#input,#i,len(#input)-#i+1))
select #ch=(SUBSTRING(#input,#i+1,1))
if(#flag=0)
begin
select #output=(SUBSTRING(#input,0,#i))
set #flag=1
end
set #output=#output+' '+#ch
end
set #i=#i+1
end
select #output=SUBSTRING(#output,0,LEN(#output))
set #output= #output+#lname
return #output
end
select dbo.FullNameToShort('Santosh Kumar Yadav')
Its convert the all middle name into one char

Try this:-
select substring('Santosh Kumar Yadav',1,charindex(' ','Santosh Kumar Yadav')+1) + reverse(substring(reverse('Santosh Kumar Yadav'),1,charindex(' ',reverse('Santosh Kumar Yadav'))))

Related

Getting the middle name from a full name field

So, I've got functions to get the first and last names, like so:
create function udf_get_first_name (#string nvarchar(100))
returns nvarchar(50)
as
begin
declare #first_name nvarchar(50)
set #string = ltrim(#string)
set #string = rtrim(#string)
if dbo.udf_get_number_of_spaces(#string) > 0
set #first_name = left(#string, charindex(' ',#string) -1)
else
set #first_name = #string
return #first_name
end
create function udf_get_last_name (#string nvarchar(100))
returns nvarchar(50)
as
begin
set #string = ltrim(#string)
set #string = rtrim(#string)
if dbo.udf_get_number_of_spaces (#string) > 0
begin
set #string = reverse(#string)
set #string = left(#string, charindex(' ', #string) -1)
set #string = reverse(#string)
end
return #string
end
I need to be able to get the middle name, and just can't wrap my head around what I've been reading through my searching so far. Not sure if I'm just being dumb or not.
I also need to be able to sort a name formatted as L/M/F, into the proper columns as well, which I'm having an even harder time with.
Edit: Not all the records have middle names.
You can use the following solution, using a function to get a part of the name or the fullname in a specified format:
--
-- function to get a part of a fullname or to reformat the fullname.
-- #fullname - the fullname to get the part from or to reformat.
-- #format - the format of the output using F (firstname), M (middlename) and L (lastname).
-- the function returns the fullname in specified format or NULL if input is not valid
-- or the part of name is empty.
--
CREATE FUNCTION GetNamePart(#fullname VARCHAR(200), #format VARCHAR(30))
RETURNS VARCHAR(200)
AS
BEGIN
-- replace multiple spaces of the fullname and trim the result.
SET #fullname = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(#fullname, ' ', '<>'), '><', ''), '<>', ' ')))
-- get the different name parts (firstname, middlename and lastname) of the fullname.
DECLARE #first_name VARCHAR(100)
SET #first_name = LTRIM(RTRIM(LEFT(#fullname, CHARINDEX(' ', #fullname))))
DECLARE #last_name VARCHAR(100)
SET #last_name = LTRIM(RTRIM(RIGHT(#fullname, CHARINDEX(' ', REVERSE(#fullname)))))
DECLARE #middle_name VARCHAR(100)
SET #middle_name = LTRIM(RTRIM(SUBSTRING(#fullname, LEN(#first_name) + 1, LEN(#fullname) - LEN(#first_name) - LEN(#last_name))))
-- init the formatted name of the fullname.
DECLARE #formatted_name VARCHAR(100)
-- return only the formatted name if format string is valid.
IF PATINDEX('%[^LMF]%', UPPER(#format)) > 0
SET #formatted_name = ''
ELSE
BEGIN
SET #format = REPLACE(REPLACE(REPLACE(#format, 'M', '##M##'), 'L', '##L##'), 'F', '##F##')
SET #formatted_name = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(UPPER(#format), '##F##', #first_name + ' '), '##M##', #middle_name + ' '), '##L##', #last_name + ' ')))
END
-- check the input (#fullname) for valid value (firstname, lastname or firstname, middlename, lastname).
IF PATINDEX('%_ %_% _%', #fullname) = 0 AND PATINDEX('%_ _%', #fullname) = 0
SET #formatted_name = ''
-- return the new formatted name and replace multiple spaces.
RETURN NULLIF(REPLACE(REPLACE(REPLACE(#formatted_name, ' ', '<>'), '><', ''), '<>', ' '), '')
END
This function GetNamePart is using two parameters (#fullname and #format). The first parameter #fullname is the fullname containing the firstname, lastname and if available the middlename. The second parameter is defining the output format of the name. You can use the letters F (firstname), M (middlename) and L (lastname) to define the format of the output.
So you can use the function GetNamePart to get the middlename of the fullname:
SELECT dbo.GetNamePart(fullname, 'M') FROM table_name
... or to reformat the fullname like this:
SELECT dbo.GetNamePart(fullname, 'LMF') FROM table_name
demo on dbfiddle.uk (demo and test cases)
But you can also use a SELECT query to get the various parts of the name without a function:
SELECT
LTRIM(RTRIM(LEFT(fullname, CHARINDEX(' ', fullname)))) AS first_name,
LTRIM(RTRIM(RIGHT(fullname, CHARINDEX(' ', REVERSE(fullname))))) AS last_name,
LTRIM(RTRIM(CASE WHEN PATINDEX('%_ %_% _%', fullname) > 0 THEN SUBSTRING(fullname, CHARINDEX(' ', fullname) + 1, (CHARINDEX(' ', fullname, CHARINDEX(' ', fullname)+1)-(CHARINDEX(' ', fullname) + 1))) ELSE '' END)) AS middle_name
FROM table_name
demo on dbfiddle.uk
Similar to Sebastian Brosch's answer. I also added the TRIM function after I saw his answer. In this query, it's not necessary. But it's something nice to have. For example, if the user added multiple spaces by mistake, this will remove that.
There might be a better or simpler way to get first, middle and last name. But this is the way I come up with at the moment.
CREATE FUNCTION dbo.SplitFullName(
#FullName NVARCHAR(MAX),
#Format NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #FN NVARCHAR(MAX);
DECLARE #MN NVARCHAR(MAX);
DECLARE #LN NVARCHAR(MAX);
DECLARE #RV NVARCHAR(MAX);
SET #FN = RTRIM(LTRIM(SUBSTRING(#FullName,0, CHARINDEX(' ',#FullName))));
SET #MN = RTRIM(LTRIM(SUBSTRING(#FullName, CHARINDEX(' ',#FullName) + 1 , LEN(#FullName) - (CHARINDEX(' ',#FullName) + CHARINDEX(' ',REVERSE(#FullName)))+1)));
SET #LN = RTRIM(LTRIM(REVERSE(SUBSTRING(REVERSE(#FullName),0, CHARINDEX(' ',REVERSE(#FullName))))));
IF (#Format='FN')
SET #RV = CASE WHEN LEN(#FN) = 0 THEN NULL ELSE #FN END;
ELSE IF (#Format='MN')
SET #RV = CASE WHEN LEN(#MN) = 0 THEN NULL ELSE #MN END;
ELSE IF (#Format='LN')
SET #RV = CASE WHEN LEN(#LN) = 0 THEN NULL ELSE #LN END;;
ELSE
SET #RV = CONCAT(#LN, ' ', CASE WHEN LEN(#MN) = 0 THEN NULL ELSE CONCAT(#MN , ' ') END, #FN);
RETURN #RV;
END;
Example 01
SELECT dbo.SplitFullName('Antonio P. Green', 'FN') AS FN,
dbo.SplitFullName('Antonio P. Green', 'MN') AS MN,
dbo.SplitFullName('Antonio P. Green', 'LN') AS LN,
dbo.SplitFullName('Antonio P. Green', 'LMF') AS LMF;
+---------+----+-------+------------------+
| FN | MN | LN | LMF |
+---------+----+-------+------------------+
| Antonio | P. | Green | Green P. Antonio |
+---------+----+-------+------------------+
Example 02
select dbo.SplitFullName('Cindy Bertha Collier Sproles', 'FN') AS FN,
dbo.SplitFullName('Cindy Bertha Collier Sproles', 'MN') AS MN,
dbo.SplitFullName('Cindy Bertha Collier Sproles', 'LN') AS LN,
dbo.SplitFullName('Cindy Bertha Collier Sproles', 'LMF') AS LMF;
+-------+----------------+---------+------------------------------+
| FN | MN | LN | LMF |
+-------+----------------+---------+------------------------------+
| Cindy | Bertha Collier | Sproles | Sproles Bertha Collier Cindy |
+-------+----------------+---------+------------------------------+
Example 03
SELECT dbo.SplitFullName('Tristan Jackson', 'FN') AS FN,
dbo.SplitFullName('Tristan Jackson', 'MN') AS MN,
dbo.SplitFullName('Tristan Jackson', 'LN') AS LN,
dbo.SplitFullName('Tristan Jackson', 'LMF') AS LMF;
+---------+------+---------+-----------------+
| FN | MN | LN | LMF |
+---------+------+---------+-----------------+
| Tristan | NULL | Jackson | Jackson Tristan |
+---------+------+---------+-----------------+
You can handle this using Multiple comma separated CTE.
declare #str nvarchar(max) ='kareena kapoor khan';
with
t0 AS (select charindex(' ',#str) pos, #str name ),
t1 AS (select charindex(' ',#str,pos+1)pos,#str name from t0)
select substring(t0.name,0,t0.pos) "firstName",
substring(t0.name,t0.pos+1,(t1.pos-t0.pos)) "MiddleName",
substring(t0.name,t1.pos+1,(len(t0.name)- t1.pos)) "Lastname"
from t0
inner join t1 on t0. name= t1.name
output
|firstName | MiddleName |Lastname
|kareena | kapoor |khan
Also, Instead of creating 3 function for first name , middle name and last name you can just create a single function and pass parameter as #namepart.
The future is start as sql-server 2016:
use STRING_SPLIT function
Use Northwind
Go
SELECT ProductID, value
FROM Products
CROSS APPLY STRING_SPLIT(ProductName, ' ');
by this query you can split names... then use by Row() function you can choose middle name.
STRING_SPLIT requires the compatibility level to be at least 130. When the level is less than 130, SQL Server is unable to find the STRING_SPLIT function.
Select Ltrim(SUBSTRING(name,CharIndex(' ',name),
CAse When (CHARINDEX(' ',name,CHARINDEX(' ',name)+1)-CHARINDEX(' ',name))<=0 then 0
else CHARINDEX(' ',name,CHARINDEX(' ',name)+1)-CHARINDEX(' ',name) end )) as MiddleName
From TableName

How to modify data retrieved from select in sql?

suppose i am having some unwanted characters in the data present in a column for eg name column in customers table has data like < ,is there anyway to modify such characters like '<' to blankspace while retrieving this data using select statement? This is to prevent xss scripts showing up due to old data which is having such unwanted characters
e.g:
select *
from customers
returns
Id Name Age city salary
-- ------ --- ---- ------
1 <hari 32 Ahmedabad 4000
2 Khilan 25 Delhi 5678
3 kaushik 23 Kota 234
i want <hari to be displayed as hari when this data is retrieved using select statement.How to achieve this ?
Something like...
SELECT REPLACE(REPLACE(a.name,'<', ''), '>','')
FROM ...
It may be better to write a function to remove special characters. Here the function replaces any character that does not look like a-z,A-Z(if case sensitive),0-9 and Space. You can add more if needed.
For example if you want to retain period(.) the use '[^a-zA-Z0-9 .]'
Function:
CREATE FUNCTION ufn_RemoveSpecialCharacters
(
#String VARCHAR(500),
#Exclude VARCHAR(100),
#CollapseSpaces BIT
)
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE #StartString INT,
#EndString INT,
#FinalString VARCHAR(500),
#CurrentString CHAR(1),
#PreviousString CHAR(1)
SET #StartString = 1
SET #EndString = LEN(ISNULL(#String, ''))
WHILE #StartString <= #EndString
BEGIN
SET #CurrentString = SUBSTRING(#String, #StartString, 1)
SET #PreviousString = SUBSTRING(#String, #StartString-1, 1)
IF #CurrentString LIKE ISNULL(#Exclude,'[^a-zA-Z0-9 ]')
BEGIN
SET #CurrentString = ''
IF #CollapseSpaces = 1
SET #FinalString = CASE WHEN #PreviousString = CHAR(32) THEN ISNULL(#FinalString, '') ELSE ISNULL(#FinalString, '')+' ' END
END
ELSE
BEGIN
SET #FinalString = ISNULL(#FinalString, '') + #CurrentString
IF #CollapseSpaces = 1
BEGIN
SET #FinalString = REPLACE(#FinalString,' ',' ')
END
END
SET #StartString = #StartString + 1
END
--PRINT #String
RETURN LTRIM(RTRIM(#FinalString))
END
GO
Usage:
Does not collapse Spaces
SELECT dbo.ufn_RemoveSpecialCharacters('This #$%string has#$% special #$% characters and spaces))', '[^a-zA-Z0-9 ]', 0)
Collapses multiple Spaces
SELECT dbo.ufn_RemoveSpecialCharacters('This #$%string has#$% special #$% characters and spaces))', '[^a-zA-Z0-9 ]', 1)
Here is the example
SELECT Replace(Column Name, ' ', '') AS C
FROM Contacts
WHERE Replace(Column Name, ' ', '') LIKE 'whatever'
Hope this was helpful

Replace Spaces in Telephone Column

I currently have a telephone number column which has spaces in between the numbers.
For example:
07595 8832 36
0161 88143 09
016188121 1 1
0 7 585 99 21 2 2
How do I replaces the spaces and get the number all together?
Example:
07595 8832 36
07595883236 (like this)
The table name is called [dbo].[NumberChecker3]
And the column in the database is called Telephone
REPLACE (phone_number, ' ', '')
Like this:
UPDATE [dbo].[NumberChecker3] SET telephone = REPLACE (telephone , ' ', '')
try:
select replace(replace( rtrim(replace(Telephone,char(160),'')) , char(9),''), ' ','')
from [dbo].[NumberChecker3]
if work fine for you then:
update [dbo].[NumberChecker3]
set Telephone = replace(replace( rtrim(replace(Telephone,char(160),'')) , char(9),''), ' ','')
try this
UPDATE [dbo].[NumberChecker3] SET [Telephone] = REPLACE (Telephone , ' ', '')
this is for the update or if you just need to get the number without space then try this
Declare #number nvarchar(10);
select #number = REPLACE (Telephone , ' ', '') From [dbo].[NumberChecker3]
Try the REPLACE method of sql server from here
like this
REPLACE(phone_number,' ','')
We can do like this aslo
DECLARE #XML VARCHAR(MAX) = '07595 8832 36'
select REPLACE(RTRIM(LTRIM(#XML)),' ','')

How to get rid of double quote from column's value?

Here is the table, each column value is wrapped with double quotes (").
Name Number Address Phone1 Fax Value Status
"Test" "10000000" "AB" "5555" "555" "555" "Active"
How to remove double quote from each column? I tried this for each column:-
UPDATE Table
SET Name = substring(Name,1,len(Name)-1)
where substring(Name,len(Name),1) = '"'
but looking for more reliable solution. This fails if any column has trailing white space
Just use REPLACE?
...
SET Name = REPLACE(Name,'"', '')
...
UPDATE Table
SET Name = REPLACE(Name, '"', '')
WHERE CHARINDEX('"', Name) <> 0
create table #t
(
Name varchar(100)
)
insert into #t(Name)values('"deded"')
Select * from #t
update #t Set Name = Coalesce(REPLACE(Name, '"', ''), '')
Select * from #t
drop table #t
Quick and Dirty, but it will work :-)
You could expand and write this as a store procedure taking in a table name, character you want to replace, character to replace with, Execute a String variable, etc...
DECLARE
#TABLENAME VARCHAR(50)
SELECT #TABLENAME = 'Locations'
SELECT 'Update ' + #TABLENAME + ' set ' + column_Name + ' = REPLACE(' + column_Name + ',''"'','''')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TABLENAME
and data_Type in ('varchar')

Convert SQL Server result set into string

I am getting the result in SQL Server as
SELECT StudentId FROM Student WHERE condition = xyz
I am getting the output like
StudentId
1236
7656
8990
........
The output parameter of the stored procedure is #studentId string and I want the return statement as
1236, 7656, 8990.
How can I convert the output in the single string?
I am returning single column [ie. StudentId]
Test this:
DECLARE #result NVARCHAR(MAX)
SELECT #result = STUFF(
( SELECT ',' + CONVERT(NVARCHAR(20), StudentId)
FROM Student
WHERE condition = abc
FOR xml path('')
)
, 1
, 1
, '')
DECLARE #result varchar(1000)
SELECT #result = ISNULL(#result, '') + StudentId + ',' FROM Student WHERE condition = xyz
select substring(#result, 0, len(#result) - 1) --trim extra "," at end
Use the COALESCE function:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = COALESCE(#StudentID + ',', '') + StudentID
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:
NULL + "Any text" => NULL
It's a very common mistake, don't forget it!
Also is good idea to use ISNULL function:
SELECT #result = #result + ISNULL(StudentId + ',', '') FROM Student
Use the CONCAT function to avoid conversion errors:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = CONCAT(COALESCE(#StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).
DECLARE #results VARCHAR(1000) = ''
SELECT #results = #results +
ISNULL(CASE WHEN LEN(#results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz
select #results
The answer from brad.v is incorrect! It won't give you a concatenated string.
Here's the correct code, almost like brad.v's but with one important change:
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE #results + ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!
Use STRING_AGG:
SELECT STRING_AGG(sub.StudentId, ',') FROM
(select * from dbo.Students where Name = 'Test3') as sub
If you want to use e.g ORDER BY:
SELECT STRING_AGG(sub.StudentId, ',') WITHIN GROUP(Order by StudentId) FROM
(select * from dbo.Students where Name = 'Test3') as sub
or a single select statement...
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
Assign a value when declaring the variable.
DECLARE #result VARCHAR(1000) ='';
SELECT #result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz