2016-12-07 65 views
0

我有一個Table Company。我需要知道公司名稱中的特殊字符是什麼。使用SQL Select提取不同的特殊字符

考慮樣品表

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

從上面的表格,我需要選擇只有鮮明的特殊字符知道什麼是所有的特殊字符都參與了公司名稱

的上表的輸出應爲/&.,

+2

你是如何定義的特殊字符?非字母,但不是空格? – jarlh

+0

如果條目僅用ASCII,則可以使用範圍查詢完成。在Unicode中可能不那麼容易。 – Namphibian

回答

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 | 
+--------------+--------------------+-----+ 
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('%[,[email protected]\.&/]%',CompanyName),1,'') CompanyName 
,SUBSTRING(CompanyName,PATINDEX('%[,[email protected]\.&/]%',CompanyName),1) spcol from @t 
union ALL 

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

select distinct spcol 

from cte