使用SQL Select提取列中的不同特殊字符

时间:2016-12-07 10:14:47

标签: sql sql-server distinct

我有一家餐桌公司。我需要知道公司名称中的所有特殊字符是什么。

考虑样本表

S.No.     CompanyName
__________________________________
1.        24/7 Customers
2.        Rose & Co.
3.        Rose Inc. Corp.
4.        Rose Pvt. Ltd.,

从上表中我需要选择不同的特殊字符,以了解 CompanyName

中涉及的所有特殊字符是什么

上表的输出应为 /&.,

2 个答案:

答案 0 :(得分:1)

有一个地方你需要定义你的"常规"字符

select  '%[^a-zA-Z0-9 ]%'
with    prm (regular_char)
        as
        (
            select  '%[^a-zA-Z0-9 ]%'
        )

       ,cte (special_char,string_suffix)
        as
        (
            select  ''              as special_char
                   ,CompanyName     as string_suffix

            from    t

            union all

            select  substring (string_suffix,special_char_ind,1)                    as special_char
                   ,substring (string_suffix,special_char_ind+1,len(string_suffix)) as string_suffix

            from   (select  string_suffix
                           ,nullif(patindex(prm.regular_char,string_suffix),0) as special_char_ind
                    from    cte,prm
                    where   string_suffix <> ''
                    )  t

            where   special_char_ind is not null

        )

select      special_char
           ,ascii(special_char) as ascii_special_char
           ,count(*)            as cnt      

from        cte

where       special_char <> ''

group by    special_char

option      (maxrecursion 0)
+--------------+--------------------+-----+
| special_char | ascii_special_char | cnt |
+--------------+--------------------+-----+
|              |  9                 | 1   |
+--------------+--------------------+-----+
| &            | 38                 | 1   |
+--------------+--------------------+-----+
| ,            | 44                 | 1   |
+--------------+--------------------+-----+
| .            | 46                 | 5   |
+--------------+--------------------+-----+
| /            | 47                 | 1   |
+--------------+--------------------+-----+

答案 1 :(得分:0)

试试这个,

declare @t table(SNo int,CompanyName varchar(30))
insert into @t VALUES
(1,'24/7 Customers')
,(2,'Rose & Co.')
,(3,'Rose Inc. Corp.')
,(4,'Rose Pvt. Ltd.,')

;With CTE as
(
select sno
,stuff(CompanyName,PATINDEX('%[,-@\.&/]%',CompanyName),1,'') CompanyName
,SUBSTRING(CompanyName,PATINDEX('%[,-@\.&/]%',CompanyName),1) spcol from @t 
union ALL

select sno,
replace(CompanyName,SUBSTRING(CompanyName,PATINDEX('%[,-@\.&/]%',CompanyName),1),'') 
,SUBSTRING(CompanyName,PATINDEX('%[,-@\.&/]%',CompanyName),1)
from cte
where PATINDEX('%[,-@\.&/]%',CompanyName)>0
)

select distinct spcol

from cte