将字符插入SQL字符串

时间:2014-02-07 01:39:13

标签: sql sql-server-2008 sql-update substring

我有大约10,000个电话号码,如:

1234567890

我需要得到它们(123)456-7890

我已经尝试了很多东西,似乎无法理解我的逻辑,这就是我现在所拥有的:

Update Contact
    SUBSTRING(Telephone1, 0, 0) + '(' +
    SUBSTRING(Telephone1, 1, 3) + ') ' +
    SUBSTRING(Telephone1, 4, 3) + '-' +
    SUBSTRING(Telephone1, 7, 4)

感谢任何建议或帮助。

由于

2 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @table TABLE
(
    Num VARCHAR(20)
)

INSERT @table 
VALUES ('1234567890'),  ('0987654321')


SELECT * 
FROM @table

UPDATE @table
SET Num = SUBSTRING(Num, 0, 0) + '(' +
    SUBSTRING(Num, 1, 3) + ') ' +
    SUBSTRING(Num, 4, 3) + '-' +
    SUBSTRING(Num, 7, 4)
FROM @table

SELECT * 
FROM @table

答案 1 :(得分:0)

尝试其中一个

--TO UPDATE --> USED THIS QUERY (RUN THIS ONCE ONLY)
UPDATE Contact SET Telephone1 = '(' + SUBSTRING(Telephone1, 1,3) + ') ' + SUBSTRING(Telephone1, 4,3) + '-' + SUBSTRING(Telephone1, 7,4)

--TO UPDATE WITH CHECKING --> USED THIS QUERY
UPDATE Contact SET Telephone1 = '(' + SUBSTRING(Telephone1, 1,3) + ') ' + SUBSTRING(Telephone1, 4,3) + '-' + SUBSTRING(Telephone1, 7,4)
WHERE NOT Telephone1 LIKE '(%'
        --AND NOT Telephone1 LIKE '%)'
        --AND NOT Telephone1 LIKE '%-%'

--UPDATE IS NECESSARY THEN USE QUERY LIKE THIS
SELECT  '(' + SUBSTRING(Telephone1, 1,3) + ') ' + SUBSTRING(Telephone1, 4,3) + '-' + SUBSTRING(Telephone1, 7,4) AS Telephone1
FROM    Contact