SQL: What are phone number formatting options? - sql

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

Related

SQL: Extract a word from a string

I have a following SQL statement that looks for a certain word after the keyword "dispatch level:".
SELECT SUBSTRING(CadRemarks, CHARINDEX('dispatch level:', CadRemarks) + LEN('dispatch level:'), 6) as
data
from myTable
I would like to upgrade this statement in a way that will return whatever comes between the keyword "dispatch level:" and anything that comes after the word that I'm looking for. So it could be another word, character, or space. For example:
Dispatch level: XXXXX YYY
or
Dispatch level: XXXXX
Only return XXXXX
EDIT
I'm trying out this SQL, but it selects the word after the word I need, as well.
select left(tt.CadRemarks, charindex(' ', tt.CadRemarks+ ' ')) as data
from myTablet cross apply
( values (substring(CadRemarks, charindex('dispatch level:', CadRemarks) +
16, len(CadRemarks)))
) tt(CadRemarks)
where t.CadRemarks like '%dispatch level:%'
the where clause is for me to limit the records, but I will have to move it and make the whole thing as CASE statement. But that's later....
Also tried this, but getting an error (invalid length parameter passed to the left...)
SELECT SUBSTRING(CadRemarks, CHARINDEX('dispatch level: ', CadRemarks) +
LEN('dispatch level: ') + 1,
CHARINDEX('', CadRemarks) - (CHARINDEX('dispatch level: ', CadRemarks) + 2 +
LEN('dispatch level: ')))
FROM myTable
Use left() to further find the string :
select left(tt.CadRemarks, charindex(' ', tt.CadRemarks+ ' ')) as data
from table t cross apply
( values (substring(CadtRemarks, charindex('dispatch level:', CadRemarks) + 16, len(CadRemarks)))
) tt(CadRemarks);

SQL functions (String Selection)

I/P : P-2120-001-A10 I need O/p As P-2120 using SQL Server Functions.
this is the given string 'P-2120-001-A10' and i need to select data from given string left of the second '-' symbol i.e 'P-2120' its should select dynamically
Whilst it isn't clear what you are asking for this will transform I/P : P-2120-001-A10 into O/p As P-2120
with sample as (
select 'I/P : P-2120-001-A10' as astring
)
select
substring(astring,7,6) AS guess1
, 'O/p As ' + substring(astring,7,6) AS guess2
from sample
After your Question edit, you could use SUBSTRING & CHARINDEX Function to read the data from string left of the second '-' symbol Dynamically.
SELECT SUBSTRING(<I/P>, 1, CHARINDEX('-', <I/P>)-1)+'-'+SUBSTRING(SUBSTRING(<I/P>, CHARINDEX('-', <I/P>)+1, LEN(<I/P>)), 1, CHARINDEX('-', SUBSTRING(<I/P>, CHARINDEX('-', <I/P>)+1, LEN(<I/P>)))-1);
Output :
P-2120

splitting a column into individual words then filter results

I have a column where I would like to break it into individual words for an "auto suggest" on text box. I was able to accomplish this thanks to this article:
http://discourse.bigdinosaur.org/t/sql-and-database-splitting-a-column-into-individual-words/709/45
However, the results have characters that I don't want like "/' , etc.
I have a database function that I use when I want to filter out characters, but I cannot figure out how to merge the 2 and get it to work.
Here's the splitting code:
;WITH for_tally (spc_loc) AS
(SELECT 1 AS spc_loc
UNION ALL
SELECT spc_loc + 1 from for_tally WHERE spc_loc < 65
)
SELECT spc_loc into #tally from for_tally OPTION(MAXRECURSION 65)
select substring(name, spc_loc, charindex(' ', name + ' ', spc_loc) - spc_loc) as word
into #temptable
from #tally, products
where spc_loc <= convert(int, len(name))
and substring(' ' + name, spc_loc, 1) = ' '
Then, here's how I view the table:
select distinct word from #temptable order by word
Then here's how I call the database function in other queries:
SELECT * INTO #Keywords FROM dbo.SplitStringPattern(#Keywords, '[abcdefghijklmnopqrstuvwxyz0123456789-]')
Where #Keywords is the string to filter.
I've tried all I can think of, to filter the first query by the dbo.SplitStringPattern function
ie:
select substring(dbo.SplitStringPattern(name, '[abcdefghijklmnopqrstuvwxyz0123456789-]'), spc_loc, charindex(' ', name + ' ', spc_loc) - spc_loc) as word
into #temptable
from #tally, products
where spc_loc <= convert(int, len(name))
and substring(' ' + name, spc_loc, 1) = ' '
But I get "Cannot find either column "dbo" or the user-defined function or aggregate "dbo.SplitStringPattern", or the name is ambiguous."
I need this to be optimized as this query needs to return results very quick.
Or, if there's a better way of doing this, I'm open to suggestions.
Create a T-SQL Function to filter out the unwanted characters before your "database function" is called. The following web page links should help.
MSDN Create Function (Transact-SQL)
How to remove special characters from a string in MS SQL Server (T-SQL)

SQL Formatting a field

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.

Sql Server Split and Concatenation

I have data in the following format in a sql server database table
[CPOID] [ContractPO] [ContractPOTitle]
1 10-SUP-CN-CNP-0001 Drytech
2 10-SUP-CN-CNP-0002 EC&M
I need to write a stored procedure to generate the following result
[CPOID] [ContractPO] [ContractPOTitle] [ConcatField]
1 10-SUP-CN-CNP-0001 Drytech CNP-0001-Drytech
2 10-SUP-CN-CNP-0002 EC&M CNP-0002-EC&M
where [ConcatField] generate the result using split the last two values of the [ContractPOTitle] column and combine with the [ContractPOTitle]
If the ContractPO field is always the same length, you could just do:
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, 8) + '-' + ContractPOTitle as [ConcatField]
FROM MyTable
Assuming that the length of the ContractPO field is not fixed AND we have to rely on stripping out the text after the next to last '-', the following SQL will work. It's a bit ugly, but these types of operations are necessary because there doesn't appear to be a LASTINDEX function available out of the box in SQL Server.
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, CHARINDEX('-', REVERSE(ContractPO), CHARINDEX('-', REVERSE(ContractPO)) + 1) - 1) + '-' + ContractPOTitle as [ConcatField]
FROM #myTable