Gestern hatte ich ja schon die Basics für SQL-CLR Integration beschrieben, heute treiben wir das mal weiter auf die Spitze: Wir wollen Regular Expressions im SQL Server nutzen.
Dazu erweitern wir uns ersteinmal die Klasse um drei neue Funktionen:
- RegEx_HasMatches soll uns sagen ob überhaupt Matches auftreten
- RegEx_MatchCount soll uns sagen wie viele Matches auftreten
- RegEx_GetMatches soll uns die Matches aufsgeben
Für die Copy+Paster unter euch ;) :
<SqlFunction()> _
Public Shared Function RegEx_HasMatches(ByVal inputstring As SqlString, ByVal regexstring As SqlString) As SqlBoolean
If Regex.Matches(inputstring.Value, regexstring.Value, RegexOptions.IgnoreCase).Count > 0 Then
Return True
Else
Return False
End If
End Function
<SqlFunction()> _
Public Shared Function RegEx_MatchCount(ByVal inputstring As SqlString, ByVal regexstring As SqlString) As SqlInt64
Return Regex.Matches(inputstring.Value, regexstring.Value, RegexOptions.IgnoreCase).Count
End Function
<SqlFunction()> _
Public Shared Sub RegEx_GetMatches(ByVal inputstring As SqlString, ByVal regexstring As SqlString)
Dim mc As MatchCollection = Regex.Matches(inputstring.Value, regexstring.Value, RegexOptions.IgnoreCase)
Dim result As New SqlDataRecord(New SqlMetaData("Match", SqlDbType.NVarChar, 4000))
Dim pipe As SqlPipe = SqlContext.Pipe
pipe.SendResultsStart(result)
For Each item As Match In mc
result.SetString(0, item.Value)
pipe.SendResultsRow(result)
Next
pipe.SendResultsEnd()
End Sub
Nach dem Bereitstellen können wir das ganze auch schon testen:
declare @inputstring nvarchar(4000) set @inputstring= 'My favorite web sites include: </P><A HREF="http://www.xentrope.de">Xylon''s Blog</A></P> <A HREF="http://dotnet-forum.de">.NET Forum</A></P> <A HREF="http://blogs.msdn.com/bclteam">.NET Base Class Library blog</A></P>' declare @regexstring nvarchar(4000) set @regexstring = 'href\s*=\s*(?:"(?<1>[^"]*)"|(?<1>\S+))' select dbo.RegEx_HasMatches(@inputstring,@regexstring) 'HasMatches' ,dbo.RegEx_MatchCount(@inputstring,@regexstring) 'Nr of Matches' exec dbo.RegEx_GetMatches @inputstring,@regexstring
Und als Ergebnisse bekommen wir:
HasMatches Nr of Matches 1 3 Match HREF="http://www.xentrope.de" HREF="http://dotnet-forum.de" HREF="http://blogs.msdn.com/bclteam"
Coole Sache! :)




Interessante Sache…