简体   繁体   English

SQL:什么是电话号码格式选项?

[英]SQL: What are phone number formatting options?

SQL: What are phone number formatting options? SQL:什么是电话号码格式选项?

I query my SQL Database for a phone number:我在 SQL 数据库中查询电话号码:

816-123-4567 816-123-4567

I want to output it is as:我想输出它是:

816 123-4567. 816 123-4567。

What steps do I take to achieve this result in an SQL environment?在 SQL 环境中我需要采取哪些步骤来实现这个结果?

Use SUBSTRING and CHARINDEX functions.使用 SUBSTRING 和 CHARINDEX 函数。

SUBSTRING gets a part of the string according to given indexes. SUBSTRING 根据给定的索引获取字符串的一部分。

CHARINDEX gets the index of the character that triggers your String separation. CHARINDEX 获取触发您的字符串分离的字符的索引。

Below is an MSSQL Server query.下面是一个 MSSQL Server 查询。 According to your DBMS, the function names can vary, but the logic will is the same.根据您的 DBMS,函数名称可能会有所不同,但逻辑是相同的。

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

A standard SQL solution would be:标准的 SQL 解决方案是:

select substring(phone, 1, 3) || ' ' || substring(phone, 5, 8)

There may be simpler solutions in other databases.其他数据库中可能有更简单的解决方案。 For instance, in SQL Server:例如,在 SQL Server 中:

select stuff(phone, 4, 1, ' ')

And in MySQL:在 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.如果您有其他格式,那么您可能需要更复杂的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM