如何在 SQL 中将数字列格式化为电话号码 [英] How to format a numeric column as phone number in SQL

查看:48
本文介绍了如何在 SQL 中将数字列格式化为电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个带有电话号码列的表.数字看起来像这样:

I have table in the database with a phone number column. The numbers look like this:

123456789

我想将其格式化为如下所示:

I want to format that to look like this:

123-456-789

推荐答案

应该这样做:

UPDATE TheTable
SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + '-' + 
                  SUBSTRING(PhoneNumber, 4, 3) + '-' + 
                  SUBSTRING(PhoneNumber, 7, 4)

结合凯恩的建议,您可以在运行时计算电话号码的格式.一种可能的方法是为此目的使用标量函数(适用于 SQL Server):

Incorporated Kane's suggestion, you can compute the phone number's formatting at runtime. One possible approach would be to use scalar functions for this purpose (works in SQL Server):

CREATE FUNCTION FormatPhoneNumber(@phoneNumber VARCHAR(10))
RETURNS VARCHAR(12)
BEGIN
    RETURN SUBSTRING(@phoneNumber, 1, 3) + '-' + 
           SUBSTRING(@phoneNumber, 4, 3) + '-' + 
           SUBSTRING(@phoneNumber, 7, 4)
END

这篇关于如何在 SQL 中将数字列格式化为电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆