SQL Formatting a field - sql

In my DB, I have a column called telephone number.
Most of the numbers are ###-###-#### some of them are ###########. How can I run a query to format all numbers to look the same?
I'd prefer:
###-###-#####

I would use a scripting langauge for something like this. In PHP:
$string = "1234567890";
$formatted_string = substr($string,0,3)."-".substr($string,3,3)."-".substr($string,6,4);

I sure hope you are dealing with U.S. (assumed from your example) phone numbers only. Once you start going international, things get tough. I also hope the variations are only the two you said... SQL isn't very good at this, but here goes.
EDIT A SQLite query, as requested. I used the SQLite documentation, specifically core functions http://www.sqlite.org/lang_corefunc.html and select statements http://sqlite.org/lang_select.html.
select SUBSTR(Phone, 1, 3) + '-' +
SUBSTR(PHONE, 4, 3) + '-' +
SUBSTR(PHONE, 7, 4)
from (
select REPLACE(REPLACE(REPLACE(REPLACE(Phone, '-', ''), '(', ''), ')', ''), ' ', '') Phone
from source
) xx
My original queries work in MS SQL.
select SUBSTRING(Phone, 1, 3) + '-' +
SUBSTRING(PHONE, 4, 3) + '-' +
SUBSTRING(PHONE, 7, 4)
from source
where CHARINDEX(Phone, '-') = 0
You might consider cleaning up all the phone numbers first. EG:
select SUBSTRING(Phone, 1, 3) + '-' +
SUBSTRING(PHONE, 4, 3) + '-' +
SUBSTRING(PHONE, 7, 4)
from (
select REPLACE(REPLACE(REPLACE(REPLACE(Phone, '-', ''), '(', ''), ')', ''), ' ', '') Phone
from source
) xx
Phone numbers can get ridiculously complex. For example, I missed periods in that clean up. I strongly recommend cleaning them up in some other code than T-SQL.

SELECT CASE WHEN LENGTH(telephone_number)=10
THEN Do Something
ELSE DEfault
END
FROM YOURTABLE;
----------
PS: This is a arbitrary solution.

Related

Show the ASCII code of each character in a string

In T-SQL, how to show the ASCII code of each character in a string?
Example of a string:
Adrs_line1
ABCD
I would like to show this:
Adrs_line1_ASCII
65|66|67|68
Currently, I do this (I increment the number manually):
ASCII(SUBSTRING(Adrs_line1, 1, 1))
The all purpose of this is to find which character break an address.
Because this code doesn't work for 5% of the addresses :
PARSENAME(REPLACE(REPLACE(ADDRESSSTREET, CHAR(13), ''), CHAR(10), '.'), 3) as Adrs_line1,
PARSENAME(REPLACE(REPLACE(ADDRESSSTREET, CHAR(13), ''), CHAR(10), '.'), 2) as Adrs_line2,
PARSENAME(REPLACE(REPLACE(ADDRESSSTREET, CHAR(13), ''), CHAR(10), '.'), 1) as Adrs_line3,
EDIT :
More information about my problem :
In our ERP, the address is shown with return carriage (line 1, line 2 and line 3). But in the database, the three lines are concatened in one string. So, I have to seperate the three lines by detecting the character that do the return carriage. Normally is char(10) or char(13), but for 5% of the adresses, it's another character that I can't find manually.
Here's something you might be able to use and adapt.
Create a table-valued function that will return any deemed "bad" characters:
create or alter function dbo.FindBadAscii (#v varchar(max))
returns table as
return
select v [Char], Ascii(v) [Ascii]
from (
select top (Len(#v)) Row_Number() over(order by (select null)) n
from master.dbo.spt_values
) d
cross apply(values(Substring(#v, d.n, 1)))x(v)
where Ascii(v)<32 and Ascii(v) not in (9,10,13)
You can then test it like so:
select * from dbo.FindBadAscii ('a' + Char(10) + 'b' + Char(20) + 'c')
This identifies any "control" characters that are not a tab/lf/cr
Result
20

SQL: What are phone number formatting options?

SQL: What are phone number formatting options?
I query my SQL Database for a phone number:
816-123-4567
I want to output it is as:
816 123-4567.
What steps do I take to achieve this result in an SQL environment?
A standard SQL solution would be:
select substring(phone, 1, 3) || ' ' || substring(phone, 5, 8)
There may be simpler solutions in other databases. For instance, in SQL Server:
select stuff(phone, 4, 1, ' ')
And in MySQL:
select insert(phone, 4, 1, ' ')
Note: These are specific the the format you have provided in your question. If you have other formats, then you might need more complicated logic.
Use SUBSTRING and CHARINDEX functions.
SUBSTRING gets a part of the string according to given indexes.
CHARINDEX gets the index of the character that triggers your String separation.
Below is an MSSQL Server query.
According to your DBMS, the function names can vary, but the logic will is the same.
Query :
SELECT
SUBSTRING('816-123-4567', 0, CHARINDEX('-', '816-123-4567') ) +
' ' +
SUBSTRING('816-123-4567', CHARINDEX('-', '816-123-4567') + 1 , LEN('816-123-4567') -
CHARINDEX('-', '816-123-4567') )
And the result :
816 123-4567
When we put your field and table name instead of static values :
SELECT
SUBSTRING(YourPhoneField, 0, CHARINDEX('-', YourPhoneField) ) +
' ' +
SUBSTRING(YourPhoneField, CHARINDEX('-', YourPhoneField) + 1 , LEN(YourPhoneField) -
CHARINDEX('-', YourPhoneField) )
FROM YourTableName

SUBSTRING Empty Value Alternatives

I have the following query which works and does what is supposed to do:
select
SUBSTRING(LastName,2,1)
+SUBSTRING(LastName,3,1)
+SUBSTRING(LastName,5,1)
+SUBSTRING(FirstName,2,1)
+SUBSTRING(FirstName,3,1)
+replace(convert(varchar, DateOfBirth,101),'/','')
+CASE WHEN GenderID = '1' Then '1' WHEN GenderID = '2' Then '2' ELSE '9' END
from
Client
However if any of the SUBSTRINGS return an empty string, it needs to be replaced with 2. For example if LastName is Bond, SUBSTRING(LastName,5,1) needs to return a 2.
How would anyone suggest this is done? I was trying to avoid something like this:
select CASE WHEN SUBSTRING('James',5,1) = '' THEN '2' ELSE SUBSTRING('James',5,1) END
I think this is the simplest method:
select (SUBSTRING(LastName + '22222', 2, 1) +
SUBSTRING(LastName + '22222', 3, 1) +
SUBSTRING(LastName + '22222', 5, 1) +
SUBSTRING(FirstName + '22222', 2, 1) +
SUBSTRING(FirstName + '22222', 3, 1) +
replace(convert(varchar(255), DateOfBirth, 101), '/', '') +
(CASE WHEN GenderID IN ('1', '2') THEN GenderID ELSE '9' END)
)
from Client;
This just adds enough '2's to the end to be sure that the substring() finds a character.
Note two other changes. I added a length parameter to varchar(). You should always use a length parameter, because the default length varies by context -- leading to hard-to-find errors. I also simplified the logic for GenderId (it assumes that GenderId is a string).
Here is one trick:
SELECT
LEFT(SUBSTRING(LastName, 2, 1) + '2', 1) AS first_part
FROM Client
Should the call to SUBSTRING return an empty string output, then the call to LEFT would return '2'. Otherwise, LEFT('#2', 1) would return the number from the call to SUBSTRING (here I use # to represent any number).
As #dnoeth pointed out in his comment, this solution would only work if the substring length is 1, which appears to be the case for your query/data.
TRY THIS: If you wish to use IIF for SQL SERVER 2012 or +
SELECT IIF (SUBSTRING('James',6,1)='', '2', SUBSTRING('James',5,1))

Finding multiple occurrences in SQLite3 database?

I am having trouble with my SQL Query to return all entries in a column which have occurred more than twice.
I have looked at other StackOverflow answers for trying to do this, and whenever I apply the same query to mine it just returns entries where the first character in the entry is the same.
For example, there are around 6 entries in the database which start off with a '-' and it returns all of them even though they are not identical matches.
Would someone be able to tell me where my query is going wrong?
I would have thought that looking for duplicates would be a standard procedure.
Here is the query I am using:
SELECT name FROM subs GROUP BY name HAVING (COUNT(name) > 1);
Here is a sample of the output:
-Johnny-
-Lady_Gaga-
-Randy_Marsh-
AJWesty
All_CAPS
NB: I am looking to find all the usernames in the database that occur more than once.
Thanks in advance!
You could try stripping the dashes off the names column. Here is one way to do that:
SELECT REPLACE(name, '-', '')
FROM subs
GROUP BY REPLACE(name, '-', '')
HAVING (COUNT(name) > 1);
But this approach runs the risk of removing dashes occurring inside a name. To avoid this, we need to do more work:
SELECT
CASE WHEN SUBSTR(name, 1, 1) = '-' AND SUBSTR(name, LENGTH(name), 1) = '-'
THEN SUBSTR(name, 2, LENGTH(name)-2)
ELSE name END AS name
FROM subs
GROUP BY
CASE WHEN SUBSTR(name, 1, 1) = '-' AND SUBSTR(name, LENGTH(name), 1) = '-'
THEN SUBSTR(name, 2, LENGTH(name)-2)
ELSE name END
HAVING COUNT(*) > 1;

How to return only records after certain character?

How to return only records after certain character?
Example:
'1-1080599'
'021-1080599'
'02 -1080599 '
Expected outcome:
'1080599'
This works if you are looking to extract every character after - and if there is only one - character in the string.
select substring(column1,charindex('-',column1)+1,len(column1)) from tablename
where charindex('-',column1) > 0
or RIGHT can be used.
select right(column1,charindex('-',column1)) from tablename
where charindex('-',column1) > 0
vkp's solution will work fine, but you could also use PARSENAME to make things slightly simpler, e.g.:
SELECT PARSENAME(REPLACE('101-2345678', '-', '.'), 1);
If you want to get rid of spaces then you could do this:
SELECT LTRIM(PARSENAME(REPLACE('101 - 2345678', '-', '.'), 1));
...or even:
SELECT PARSENAME(REPLACE(REPLACE('101 - 2345678', '-', '.'), ' ', ''), 1);