从Sql Server中删除一些符号

时间:2016-01-08 03:13:01

标签: sql-server

朋友:

我想在sql-server中为地址表更新一些非标准填充,这是我的数据:

country       state
China         shang(here have Tab key filed)hai
Japan         Tokyo,
England       London(here have Enter key filed)
……

我想要的结果是:

country       state
China         shanghai
Japan         Tokyo
England       London
……

我不知道如何实现它。谁能帮我? 谢谢!

2 个答案:

答案 0 :(得分:3)

下面的代码删除了标签,新行和回车..

UPDATE <table>
SET state = REPLACE(REPLACE(REPLACE(state, CHAR(9), ''), CHAR(10), ''), CHAR(13), '');

/*
CHAR(9)     - Tab
CHAR(10)    - New Line
CHAR(13)    - Carriage Return
*/

答案 1 :(得分:0)

假设在tab,换行符和逗号之外可能还有其他“非标准”的东西,并且“state”列中应该只有字母和空格的东西,以下内容应该产生所需的结果:

WITH CTE AS (
    SELECT Country
        , CASE WHEN PATINDEX('%[^a-z ]%', [State]) > 0 THEN SUBSTRING([State], 1, PATINDEX('%[^a-z ]%', [State]) - 1)
            ELSE [State] END StatePart
        , CASE WHEN PATINDEX('%[^a-z ]%', [State]) > 0 THEN SUBSTRING([State], PATINDEX('%[^a-z ]%', [State]) + 1, LEN([State])) ELSE '' END SubState
    FROM tblName
    UNION ALL
    SELECT tt.Country
        , CASE WHEN PATINDEX('%[^a-z ]%', SubState) > 0 THEN SUBSTRING(SubState, 1, PATINDEX('%[^a-z ]%', SubState) - 1)
            ELSE SubState END
        , CASE WHEN PATINDEX('%[^a-z ]%', SubState) > 0 THEN SUBSTRING(SubState, PATINDEX('%[^a-z ]%', SubState) + 1, LEN(SubState)) ELSE '' END
    FROM tblName
    JOIN CTE ON CTE.Country = tblName.Country
    WHERE SubState <> '' 
    --AND PATINDEX('%[a-z ]%', SubState) > 0
    )
UPDATE tblName
SET [State] = STUFF((SELECT StatePart + ''
        FROM CTE
        WHERE Country = T.Country
        FOR XML PATH ('')),1,0,'') 
FROM CTE T 
JOIN tblName ON tblName.Country = T.Country
-- SELECT Country, [State] FROM tblName

如果您还可以在“州”列中填写“非标准”空格,那么您需要删除此处PATINDEX的方括号中的每个空格。问题是这也会删除任何合法的空间。