如何将数值字符串拆分为SQL Server中的数字

时间:2018-06-06 14:46:11

标签: sql sql-server tsql

ID  PHONE
1   9701245929
2   66663333
3   9701245931
4   9701245932
5   26668888
6   48228899
7   88229933

输出:

ID  PHONE
1   9701 245 929
2   6666 3333
3   9701 245 931
4   9701 245 932
5   2666 8888
6   4822 8899
7   8822 9933

3 个答案:

答案 0 :(得分:2)

您可以使用下面的查询 See working demo

select id,
phone=case 
    when 
        len(phone)=10 
    then
        FORMAT(cast(phone as bigint), '### ### ###')  
     when 
        len(phone)=8 
    then
        FORMAT(cast(phone as bigint), '#### ####') 
end
from t;

答案 1 :(得分:1)

您可以使用大小写并构建其他人建议的字符串或格式。

SELECT
  id
 ,CASE 
    WHEN LEN(phone) = 10 THEN SUBSTRING(phone, 1, 4) + ' ' + SUBSTRING(phone, 5, 3) + ' ' + SUBSTRING(phone, 8, 3)
    WHEN LEN(phone) = 8 THEN LEFT(phone, 4) + ' ' + RIGHT(phone, 4)
  END
FROM YourTable

答案 2 :(得分:0)

您需要format()

select format(PHONE, '### ### ###') as Phone
from table t;

Edit:您可以将案例表达用于条件格式

select *, (case when len(Phone) = 8
                 then format(Phone, '#### ####')
                 else format(Phone, '#### ### ###')
            end) as Phone
from table t;