Replace Spaces in Telephone Column - sql

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)),' ','')

Related

How can I split name in 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'))))

Removing spaces in complex names

I am trying to insert complex names like Juan Carlos but I want to remove all the spaces except the one between Juan and Carlos. Lets use # as space to see spaces better.
When inserting I have tried RTRIM(LTRIM(#Name)) however It seems not to work, I tried to insert ###Jua#Car### but when I select the field with DATALENGTH([Name]) I get the lenght of 14.
As I see that string I can count 13 characters, not 14.
1. What is the character I cannot count?
2. How can I end up getting Juan#Carlos removing all the spaces if LTRIM and RTRIM does not work?
Update with more info:
The column datatype is nvarchar(100)
I just tried REPLACE([Name], ' ','') and the lenght i get is 12
You can trim non-alphanumeric characters using a somewhat complicated method:
select t2.name2
from t outer apply
(select (case when name like '%[a-zA-Z0-9]%'
then stuff(t.name, 1, patindex(t.name, '%[a-zA-Z0-9]%'), '')
else ''
end) as name1
) t1 outer apply
(select (case when name1 like '%[a-zA-Z0-9]%'
then left(t1.name1,
len(t1.name1) - patindex(reverse(t.name), '%[a-zA-Z0-9.]%')
)
else ''
end) as name2
) t2
Try to use in following, select separately FirstName, LastName and concat them with space:
DECLARE #FullName VARCHAR(MAX) = ' Juan Carlos '
SELECT LEN(SUBSTRING(LTRIM(RTRIM(#FullName)), 1, CHARINDEX(' ', LTRIM(RTRIM(#FullName))) - 1) + ' ' +
REVERSE(SUBSTRING(REVERSE(LTRIM(RTRIM(#FullName))), 1,
CHARINDEX(' ', REVERSE(LTRIM(RTRIM(#FullName)))) - 1) )) AS [Len]
It returning len = 11

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

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')

SQL method to replace repeating blanks with single blanks

Is there a more elegant way of doing this. I want to replace repeating blanks with single blanks....
declare #i int
set #i=0
while #i <= 20
begin
update myTable
set myTextColumn = replace(myTextColumn, ' ', ' ')
set #i=#i+1
end
(its sql server 2000 - but I would prefer generic SQL)
This works:
UPDATE myTable
SET myTextColumn =
REPLACE(
REPLACE(
REPLACE(myTextColumn
,' ',' '+CHAR(1)) -- CHAR(1) is unlikely to appear
,CHAR(1)+' ','')
,CHAR(1),'')
WHERE myTextColumn LIKE '% %'
Entirely set-based; no loops.
So we replace any two spaces with an unusual character and a space. If we call the unusual character X, 5 spaces become: ' X X ' and 6 spaces become ' X X X'. Then we replace 'X ' with the empty string. So 5 spaces become ' ' and 6 spaces become ' X'. Then, in case there was an even number of spaces, we remove any remaining 'X's, leaving a single space.
Here is a simple set based way that will collapse multiple spaces into a single space by applying three replaces.
DECLARE #myTable TABLE (myTextColumn VARCHAR(50))
INSERT INTO #myTable VALUES ('0Space')
INSERT INTO #myTable VALUES (' 1 Spaces 1 Spaces. ')
INSERT INTO #myTable VALUES (' 2 Spaces 2 Spaces. ')
INSERT INTO #myTable VALUES (' 3 Spaces 3 Spaces. ')
INSERT INTO #myTable VALUES (' 4 Spaces 4 Spaces. ')
INSERT INTO #myTable VALUES (' 5 Spaces 5 Spaces. ')
INSERT INTO #myTable VALUES (' 6 Spaces 6 Spaces. ')
select replace(
replace(
replace(
LTrim(RTrim(myTextColumn)), ---Trim the field
' ',' |'), ---Mark double spaces
'| ',''), ---Delete double spaces offset by 1
'|','') ---Tidy up
AS SingleSpaceTextColumn
from #myTable
Your Update statement can now be set based:
update #myTable
set myTextColumn = replace(
replace(
replace(
LTrim(RTrim(myTextColumn)),
' ',' |'),
'| ',''),
'|','')
Use an appropriate Where clause to limit the Update to only the rows that have you need to update or maybe have double spaces.
Example:
where 1<=Patindex('% %', myTextColumn)
I have found an external write up on this method: REPLACE Multiple Spaces with One
select
string = replace(
replace(
replace(' select single spaces',' ','<>')
,'><','')
,'<>',' ')
Replace duplicate spaces with a single space in T-SQL
SELECT 'starting...' --sets ##rowcount
WHILE ##rowcount <> 0
update myTable
set myTextColumn = replace(myTextColumn, ' ', ' ')
where myTextColumn like '% %'
Not very SET Based but a simple WHILE would do the trick.
CREATE TABLE #myTable (myTextColumn VARCHAR(32))
INSERT INTO #myTable VALUES ('NoSpace')
INSERT INTO #myTable VALUES ('One Space')
INSERT INTO #myTable VALUES ('Two Spaces')
INSERT INTO #myTable VALUES ('Multiple Spaces .')
WHILE EXISTS (SELECT * FROM #myTable WHERE myTextColumn LIKE '% %')
UPDATE #myTable
SET myTextColumn = REPLACE(myTextColumn, ' ', ' ')
WHERE myTextColumn LIKE '% %'
SELECT * FROM #myTable
DROP TABLE #myTable
Step through the characters one by one, and maintain a record of the previous character. If the current character is a space, and the last character is a space, stuff it.
CREATE FUNCTION [dbo].[fnRemoveExtraSpaces] (#Number AS varchar(1000))
Returns Varchar(1000)
As
Begin
Declare #n int -- Length of counter
Declare #old char(1)
Set #n = 1
--Begin Loop of field value
While #n <=Len (#Number)
BEGIN
If Substring(#Number, #n, 1) = ' ' AND #old = ' '
BEGIN
Select #Number = Stuff( #Number , #n , 1 , '' )
END
Else
BEGIN
SET #old = Substring(#Number, #n, 1)
Set #n = #n + 1
END
END
Return #number
END
GO
select [dbo].[fnRemoveExtraSpaces]('xxx xxx xxx xxx')
Here is a Simplest solution :)
update myTable
set myTextColumn = replace(replace(replace(LTrim(RTrim(myTextColumn )),' ','<>'),'><',''),'<>',' ')
create table blank(
field_blank char(100))
insert into blank values('yyy yyyy')
insert into blank values('xxxx xxxx')
insert into blank values ('xxx xxx')
insert into blank values ('zzzzzz zzzzz')
update blank
set field_blank = substring(field_blank,1,charindex(' ',field_blank)-1) + ' ' + ltrim(substring(field_blank,charindex(' ',field_blank) + 1,len(field_blank)))
where CHARINDEX (' ' , rtrim(field_blank)) > 1
select * from blank
For me the above examples almost did a trick but I needed something that was more stable and independent of the table or column or a set number of iterations. So this is my modification from most of the above queries.
CREATE FUNCTION udfReplaceAll
(
#OriginalText NVARCHAR(MAX),
#OldText NVARCHAR(MAX),
#NewText NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
WHILE (#OriginalText LIKE '%' + #OldText + '%')
BEGIN
SET #OriginalText = REPLACE(#OriginalText,#OldText,#NewText)
END
RETURN #OriginalText
END
GO
Lets say, your Data like this
Table name : userdata Field: id, comment, status,
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
id, "I love -- -- - -spaces -- - my INDIA" , "Active" <br>
So just do like this
update userdata set comment=REPLACE(REPLACE(comment," ","-SPACEHERE-"),"-SPACEHERE"," ");
I didn't tested , but i think this will work.
Try this:
UPDATE Ships
SET name = REPLACE(REPLACE(REPLACE(name, ' ', ' ' + CHAR(1)), CHAR(1) + ' ', ''), CHAR(1), '')
WHERE name LIKE '% %'
REPLACE(REPLACE(REPLACE(myTextColumn,' ',' %'),'% ',''),'%','')
Statement above worked terrifically for replacing multiple spaces with a single space. Optionally add LTRIM and RTRIM to remove spaces at the beginning.
Got it from here: http://burnignorance.com/database-tips-and-tricks/remove-multiple-spaces-from-a-string-using-sql-server/
WHILE
(SELECT count(myIDcolumn)
from myTable where myTextColumn like '% %') > 0
BEGIN
UPDATE myTable
SET myTextColumn = REPLACE(myTextColumn ,' ',' ')
END
Try it:
CREATE OR REPLACE FUNCTION REM_SPACES (TEXTO VARCHAR(2000))
RETURNS VARCHAR(2000)
LANGUAGE SQL
READS SQL DATA
BEGIN
SET TEXTO = UPPER(LTRIM(RTRIM(TEXTO)));
WHILE LOCATE(' ',TEXTO,1) >= 1 DO
SET TEXTO = REPLACE(TEXTO,' ',' ');
END WHILE;
RETURN TEXTO;
END
Update myTable set myTextColumn = replace(myTextColumn, ' ', ' ');
The above query will remove all the double blank spaces with single blank space
But this would work only once.