I have an old Phone table which has a PhonoNo column with length 15. Now I am working on a task for phone number cleanup with trailing 0s after 10 digits.
+----------------+---------------+
| PhoneNo | Desire output |
+----------------+---------------+
|198765432100000 | 1987654321 |
| 198765432100 | 1987654321 |
| 1987653210 | 1987653210 |
| 19876543210 | 1987654321 |
|198765432100100 | 1987654321001 |
| 19876543 | 19876543 |
| 009876543 | 009876543 |
+----------------+---------------+
I am using the below code but it does not work for me.
SELECT PhoneNo, REPLACE(LTRIM(REPLACE(PhoneNo,'0',' ')),' ','0') as NewPhoneNo
FROM tblPhone WITH(NOLOCK)
I am looking for a solution in SQL Server to remove trailing 0s without creating any function.
A possible option is the TRIM()
function. By default the TRIM()
function removes the space character or other specified characters from the start and end of a string, so you need to put an additional character ( #
in the example) at the correct positions (1st and 10th) and remove it after that:
SELECT
REPLACE(
TRIM('0' FROM '#' + SUBSTRING(PhoneNo, 1, 10) + '#' + SUBSTRING(PhoneNo, 11, 5)),
'#',
''
) AS PhoneNo
FROM (VALUES
('19876543210000'),
('198765432100'),
('1987653210'),
('19876543210'),
('198765432100100'),
('19876543'),
('009876543')
) t (PhoneNo)
Result:
PhoneNo
-------------
1987654321
1987654321
1987653210
1987654321
1987654321001
19876543
009876543
You could use a CASE
expression to return values with less than or equal to 10 characters as they are, then then REPLACE
and RTRIM
to remove the trailing 0's:
SELECT CASE WHEN LEN(PhoneNo) <= 10 THEN PhoneNo
ELSE REPLACE(RTRIM(REPLACE(PhoneNo,'0',' ')),' ','0')
END
FROM (VALUES ('198765432100000'),
('198765432100'),
('1987653210'),
('19876543210'),
('198765432100100'),
('19876543'),
('009876543'))V(PhoneNo);
You can use a combination of string functions LEFT
PATINDEX
REVERSE
as follows:
SELECT PhoneNo,
Left(PhoneNo,
IIF(Len(PhoneNo)-PATINDEX('%[1-9]%',Reverse(PhoneNo))+1<=10 Or PhoneNo Like '%[^1-9]%',
10,
Len(PhoneNo)-PATINDEX('%[1-9]%', Reverse(PhoneNo))+1)) As NewPhoneNo
FROM tblPhone
Output:
PhoneNo NewPhoneNo
-------------------- --------------------
19876543210000 1987654321
198765432100 1987654321
1987653210 1987653210
19876543210 1987654321
198765432100100 1987654321001
19876543 19876543
009876543 009876543
or shorter:
SELECT IIF(LEN(PhoneNo) <= 10, PhoneNo, REPLACE(RTRIM(REPLACE(PhoneNo, '0', ' ')), ' ', '0'))
[This is based on Larnu's answer]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.