避免使用SQL Server中的特殊符号

时间:2016-03-18 03:48:18

标签: sql-server sql-server-2008

我对SQL Server有疑问。

Emp

Id     | Name
-------+-------------------
1      |test“te d'abc
2      |anr¤a
3      | gs-re-C“te d'ab
4      |M‚fe, DF
5      |R™temd
6      |™jad”ji
7      |Cje y ret¢n
8      |J™kl™balu
9      |le“ne-iokd
10     |liode-Pyr‚n‚ie
11     |V„s G”ta
12     |Sƒo Paulo
13     |vAstra gAtaland
14     |¥uble / Bio-Bio
15     |U“pl™n/ds VAsb-y

我需要用空值替换特殊字符。

根据上表,我想输出如下所示的内容。我试过这样:

select 
    REPLACE(state, SUBSTRING(state, PATINDEX('%[^"a-z"]%', state), 1), '') as name,
    id 
from emp

此查询未返回预期结果。

输出是:

Id     | Name
-------+-------------
1      |testtedabc
2      |anra
3      |gsreCedab
4      |MfeDF
5      |Rtemd
6      |jadji
7      |Cjeyretn
8      |Jkbalu
9      |eneiokd
10     |iodePyrnie
11     |VsGta
12     |SoPaulo
13     |vAstragAtaand
14     |ubleBioBio
15     |UpndsVAsby

请告诉我如何编写查询以在SQL Server中实现此任务。

1 个答案:

答案 0 :(得分:2)

  

以下是重复问题相同答案的link

您需要一个基于模式的分割器。这是一个取自Dwain Camp的article

-- PatternSplitCM will split a string based on a pattern of the form 
-- supported by LIKE and PATINDEX 
-- 
-- Created by: Chris Morris 12-Oct-2012 
CREATE FUNCTION [dbo].[PatternSplitCM]
(
       @List                VARCHAR(8000) = NULL
       ,@Pattern            VARCHAR(50)
) RETURNS TABLE WITH SCHEMABINDING 
AS 

RETURN
    WITH numbers AS (
        SELECT TOP(ISNULL(DATALENGTH(@List), 0))
            n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
        FROM
        (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d (n),
        (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n),
        (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n),
        (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g (n)
    )

    SELECT
        ItemNumber = ROW_NUMBER() OVER(ORDER BY MIN(n)),
        Item = SUBSTRING(@List,MIN(n),1+MAX(n)-MIN(n)),
        [Matched]
    FROM (
        SELECT n, y.[Matched], Grouper = n - ROW_NUMBER() OVER(ORDER BY y.[Matched],n)
        FROM numbers
        CROSS APPLY (
            SELECT [Matched] = CASE WHEN SUBSTRING(@List,n,1) LIKE @Pattern THEN 1 ELSE 0 END
        ) y
    ) d
    GROUP BY [Matched], Grouper

既然你有一个基于模式的分割器,你需要拆分与模式'[a-z]匹配的字符串,然后将它们连接起来以获得所需的结果:

SELECT e.Id, x.Name
FROM emp e
CROSS APPLY(
    SELECT Item + ''
    FROM dbo.PatternSplitCM(e.state, '[a-z]')
    WHERE Matched = 1
    ORDER BY ItemNumber
    FOR XML PATH('')
) x (Name)

SQL Fiddle

结果:

| Id |           Name |
|----|----------------|
|  1 |     testtedabc |
|  2 |           anra |
|  3 |     gsreCtedab |
|  4 |          MfeDF |
|  5 |          Rtemd |
|  6 |          jadji |
|  7 |       Cjeyretn |
|  8 |        Jklbalu |
|  9 |       leneiokd |
| 10 |    liodePyrnie |
| 11 |          VsGta |
| 12 |        SoPaulo |
| 13 | vAstragAtaland |
| 14 |     ubleBioBio |
| 15 |    UplndsVAsby |