How to remove the first character if it is a speci

2020-08-12 08:54发布

I currently have a table Telephone it has entries like the following:

9073456789101
+773456789101
0773456789101

What I want to do is remove only the 9 from the start of all the entries that have a 9 there but leave the others as they are.

any help would be greatly appreciated.

7条回答
Melony?
2楼-- · 2020-08-12 09:37
UPDATE dbo.Telephone 
  SET column_name = SUBSTRING(column_name, 2, 255)
  WHERE column_name LIKE '9%';
查看更多
Emotional °昔
3楼-- · 2020-08-12 09:45
Update Telephone set number = RIGHT(number,LEN(number)-1) WHERE number LIKE '9%';
查看更多
放我归山
4楼-- · 2020-08-12 09:53

I recently solved a similar problem with a combination of RIGHT(), LEN() & PATINDEX(). PATINDEX will return the integer 1 when it finds a 9 as the first character and 0 otherwise. This method allows all records to be returned at once without a CASE WHEN statement.

SELECT
    RIGHT(number, LEN(number) - PATINDEX('9%', number))
FROM Telephone
查看更多
Juvenile、少年°
5楼-- · 2020-08-12 09:54

While all other answer are probably also working, I'd suggest to try and use STUFF function to easily replace a part of the string.

UPDATE Telephone
SET number = STUFF(number,1,1,'')
WHERE number LIKE '9%'

SQLFiddle DEMO

查看更多
我命由我不由天
6楼-- · 2020-08-12 09:56
DECLARE @STR nvarchar(200) = 'TEST'
SET @STR = STUFF(@STR,1,1,'')
PRINT @STR

Result will be "EST"

查看更多
趁早两清
7楼-- · 2020-08-12 09:57

Here is the code and a SQLFiddle

SELECT CASE 
WHEN substring(telephone_number, 1, 1) <> '9'
  THEN telephone_number
ELSE substring(telephone_number, 2, LEN(telephone_number))
END
FROM Telephone
查看更多
登录 后发表回答