SqlServer類(lèi)似正則表達(dá)式的字符處理問(wèn)題
SQL Serve提供了簡(jiǎn)單的字符模糊匹配功能,比如:like, patindex,不過(guò)對(duì)于某些字符處理場(chǎng)景還顯得并不足夠,日常碰到的幾個(gè)問(wèn)題有:
1. 同一個(gè)字符/字符串,出現(xiàn)了多少次
2. 同一個(gè)字符,第N次出現(xiàn)的位置
3. 多個(gè)相同字符連續(xù),合并為一個(gè)字符
4. 是否為有效IP/身份證號(hào)/手機(jī)號(hào)等
一. 同一個(gè)字符/字符串,出現(xiàn)了多少次
同一個(gè)字符,將其替換為空串,即可計(jì)算
declare @text varchar(1000) declare @str varchar(10) set @text = 'ABCBDBE' set @str = 'B' select len(@text) - len(replace(@text,@str,''))
同一個(gè)字符串,仍然是替換,因?yàn)槭嵌鄠€(gè)字符,方法1替換后需要做一次除法;方法2替換時(shí)增加一個(gè)字符,則不需要
--方法1 declare @text varchar(1000) declare @str varchar(10) set @text = 'ABBBCBBBDBBBE' set @str = 'BBB' select (len(@text) - len(replace(@text,@str,'')))/len(@str) --方法2 declare @text varchar(1000) declare @str varchar(10) set @text = 'ABBBCBBBDBBBE' set @str = 'BBB' select len(replace(@text,@str,@str+'_')) - len(@text)
二. 同一個(gè)字符/字符串,第N次出現(xiàn)的位置
SQL SERVER定位字符位置的函數(shù)為CHARINDEX:
CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )
可以從指定位置起開(kāi)始檢索,但是不能取第N次出現(xiàn)的位置,需要自己寫(xiě)SQL來(lái)補(bǔ)充,有以下幾種思路:
1. 自定義函數(shù), 循環(huán)中每次為charindex加一個(gè)計(jì)數(shù),直到為N
if object_id('NthChar','FN') is not null drop function Nthchar GO create function NthChar ( @source_string as nvarchar(4000), @sub_string as nvarchar(1024), @nth as int ) returns int as begin declare @postion int declare @count int set @postion = CHARINDEX(@sub_string, @source_string) set @count = 0 while @postion > 0 begin set @count = @count + 1 if @count = @nth begin break end set @postion = CHARINDEX(@sub_string, @source_string, @postion + 1) End return @postion end GO --select dbo.NthChar('abcabc','abc',2) --4
2. 通過(guò)CTE,對(duì)待處理的整個(gè)表字段操作, 遞歸中每次為charindex加一個(gè)計(jì)數(shù),直到為N
if object_id('tempdb..#T') is not null drop table #T create table #T ( source_string nvarchar(4000) ) insert into #T values (N'我們我們') insert into #T values (N'我我哦我') declare @sub_string nvarchar(1024) declare @nth int set @sub_string = N'我們' set @nth = 2 ;with T(source_string, starts, pos, nth) as ( select source_string, 1, charindex(@sub_string, source_string), 1 from #t union all select source_string, pos + 1, charindex(@sub_string, source_string, pos + 1), nth+1 from T where pos > 0 ) select source_string, pos, nth from T where pos <> 0 and nth = @nth order by source_string, starts --source_string pos nth --我們我們 3 2
3. 借助數(shù)字表 (tally table),到不同起點(diǎn)位置去做charindex,需要先自己構(gòu)造個(gè)數(shù)字表
--numbers/tally table IF EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Numbers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE dbo.Numbers --===== Create and populate the Tally table on the fly SELECT TOP 1000000 IDENTITY(int,1,1) AS number INTO dbo.Numbers FROM master.dbo.syscolumns sc1, master.dbo.syscolumns sc2 --===== Add a Primary Key to maximize performance ALTER TABLE dbo.Numbers ADD CONSTRAINT PK_numbers_number PRIMARY KEY CLUSTERED (number) --===== Allow the general public to use it GRANT SELECT ON dbo.Numbers TO PUBLIC --以上數(shù)字表創(chuàng)建一次即可,不需要每次都重復(fù)創(chuàng)建 DECLARE @source_string nvarchar(4000), @sub_string nvarchar(1024), @nth int SET @source_string = 'abcabcvvvvabc' SET @sub_string = 'abc' SET @nth = 2 ;WITH T AS ( SELECT ROW_NUMBER() OVER(ORDER BY number) AS nth, number AS [Position In String] FROM dbo.Numbers n WHERE n.number <= LEN(@source_string) AND CHARINDEX(@sub_string, @source_string, n.number)-number = 0 ----OR --AND SUBSTRING(@source_string,number,LEN(@sub_string)) = @sub_string ) SELECT * FROM T WHERE nth = @nth
4. 通過(guò)CROSS APPLY結(jié)合charindex,適用于N值較小的時(shí)候,因?yàn)镃ROSS APPLY的次數(shù)要隨著N的變大而增加,語(yǔ)句也要做相應(yīng)的修改
declare @T table ( source_string nvarchar(4000) ) insert into @T values ('abcabc'), ('abcabcvvvvabc') declare @sub_string nvarchar(1024) set @sub_string = 'abc' select source_string, p1.pos as no1, p2.pos as no2, p3.pos as no3 from @T cross apply (select (charindex(@sub_string, source_string))) as P1(Pos) cross apply (select (charindex(@sub_string, source_string, P1.Pos+1))) as P2(Pos) cross apply (select (charindex(@sub_string, source_string, P2.Pos+1))) as P3(Pos)
5. 在SSIS里有內(nèi)置的函數(shù),但T-SQL中并沒(méi)有
--FINDSTRING in SQL Server 2005 SSIS FINDSTRING([yourColumn], "|", 2), --TOKEN in SQL Server 2012 SSIS TOKEN(Col1,"|",3)
注:不難發(fā)現(xiàn),這些方法和字符串拆分的邏輯是類(lèi)似的,只不過(guò)一個(gè)是定位,一個(gè)是截取,如果要獲取第N個(gè)字符左右的一個(gè)/多個(gè)字符,有了N的位置,再結(jié)合substring去截取即可;
三. 多個(gè)相同字符連續(xù),合并為一個(gè)字符
最常見(jiàn)的就是把多個(gè)連續(xù)的空格合并為一個(gè)空格,解決思路有兩個(gè):
1. 比較容易想到的就是用多個(gè)replace
但是究竟需要replace多少次并不確定,所以還得循環(huán)多次才行
--把兩個(gè)連續(xù)空格替換成一個(gè)空格,然后循環(huán),直到charindex檢查不到兩個(gè)連續(xù)空格 declare @str varchar(100) set @str='abc abc kljlk kljkl' while(charindex(' ',@str)>0) begin select @str=replace(@str,' ',' ') end select @str
2. 按照空格把字符串拆開(kāi)
對(duì)每一段拆分開(kāi)的字符串trim或者replace后,再用一個(gè)空格連接,有點(diǎn)繁瑣,沒(méi)寫(xiě)代碼示例,如何拆分字符串可參考:“第N次出現(xiàn)的位置”;
四. 是否為有效IP/身份證號(hào)/手機(jī)號(hào)等
類(lèi)似IP/身份證號(hào)/手機(jī)號(hào)等這些字符串,往往都有自身特定的規(guī)律,通過(guò)substring去逐位或逐段判斷是可以的,但SQL語(yǔ)句的方式往往性能不佳,建議嘗試正則函數(shù),見(jiàn)下。
五. 正則表達(dá)式函數(shù)
1. Oracle
從10g開(kāi)始,可以在查詢(xún)中使用正則表達(dá)式,它通過(guò)一些支持正則表達(dá)式的函數(shù)來(lái)實(shí)現(xiàn):
Oracle 10 g REGEXP_LIKE REGEXP_REPLACE REGEXP_INSTR REGEXP_SUBSTR Oracle 11g (新增) REGEXP_COUNT
Oracle用REGEXP函數(shù)處理上面幾個(gè)問(wèn)題:
(1) 同一個(gè)字符/字符串,出現(xiàn)了多少次
select length(regexp_replace('123-345-566', '[^-]', '')) from dual; select REGEXP_COUNT('123-345-566', '-') from dual; --Oracle 11g
(2) 同一個(gè)字符/字符串,第N次出現(xiàn)的位置
不需要正則,ORACLE的instr可以直接查找位置:
instr('source_string','sub_string' [,n][,m])
n表示從第n個(gè)字符開(kāi)始搜索,缺省值為1,m表示第m次出現(xiàn),缺省值為1。
select instr('abcdefghijkabc','abc', 1, 2) position from dual;
(3) 多個(gè)相同字符連續(xù),合并為一個(gè)字符
select regexp_replace(trim('agc f f '),'\s+',' ') from dual;
(4) 是否為有效IP/身份證號(hào)/手機(jī)號(hào)等
--是否為有效IP WITH IP AS( SELECT '10.20.30.40' ip_address FROM dual UNION ALL SELECT 'a.b.c.d' ip_address FROM dual UNION ALL SELECT '256.123.0.254' ip_address FROM dual UNION ALL SELECT '255.255.255.255' ip_address FROM dual ) SELECT * FROM IP WHERE REGEXP_LIKE(ip_address, '^(([0-9]{1}|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]{1}|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$'); --是否為有效身份證/手機(jī)號(hào),暫未舉例
2. SQL Server
目前最新版本為SQL Server 2017,還沒(méi)有對(duì)REGEXP函數(shù)的支持,需要通用CLR來(lái)擴(kuò)展,如下為CLR實(shí)現(xiàn)REG_REPLACE:
--1. 開(kāi)啟 CLR EXEC sp_configure 'show advanced options' , '1' GO RECONFIGURE GO EXEC sp_configure 'clr enabled' , '1' GO RECONFIGURE GO EXEC sp_configure 'show advanced options' , '0'; GO
2. 創(chuàng)建 Assembly
--3. 創(chuàng)建 CLR 函數(shù) CREATE FUNCTION [dbo].[regex_replace](@input [nvarchar](4000), @pattern [nvarchar](4000), @replacement [nvarchar](4000)) RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER, RETURNS NULL ON NULL INPUT AS EXTERNAL NAME [RegexUtility].[RegexUtility].[RegexReplaceDefault] GO --4. 使用regex_replace替換多個(gè)空格為一個(gè)空格 select dbo.regex_replace('agc f f ','\s+',' ');
注:通過(guò)CLR實(shí)現(xiàn)更多REGEXP函數(shù),如果有高級(jí)語(yǔ)言開(kāi)發(fā)能力,可以自行開(kāi)發(fā);或者直接使用一些開(kāi)源貢獻(xiàn)也行,比如:http://devnambi.com/2016/sql-server-regex/
小結(jié):
1. 非正則SQL語(yǔ)句的思路,對(duì)不同數(shù)據(jù)庫(kù)往往都適用;
2. 正則表達(dá)式中的規(guī)則(pattern) 在不同開(kāi)發(fā)語(yǔ)言里,有很多語(yǔ)法是相通的,通常是遵守perl或者linux shell中的sed等工具的規(guī)則;
3. 從性能上來(lái)看,通用SQL判斷 > REGEXP函數(shù) > 自定義SQL函數(shù)。
總結(jié)
以上所述是小編給大家介紹的SqlServer類(lèi)似正則表達(dá)式的字符處理問(wèn)題,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)本站網(wǎng)站的支持!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。