簡體   English   中英

SQL提取子字符串

[英]SQL Extract substring

我在提取SQL查詢結果中的子字符串時遇到問題。

情況是這樣:我有一個包含以下格式的字符串的列:“ ax123456uhba”,“ ax54232hrg”,“ ax274895rt”,“ ax938477ed1”,“ ax73662633wnn2”

我需要提取數字字符串,該數字字符串在字母之前和之后。 但是,偶爾在結尾的字符串中有一個我不需要的數字。 尾隨字符的長度不是靜態的,所以我不能只做一個簡單的子字符串函數。

我不一定要求提供完整的代碼,如果可能的話,只是向正確的方向提供幫助。

在此先感謝您的幫助。

看起來PATINDEX是您所需要的。

返回在字符串中找到的模式的第一個索引-需要正則表達式,請參見此-> http://blog.sqlauthority.com/2007/05/13/sql-server-udf-function-to-parse-alphanumeric-characters -從字符串/

這是此處復制的代碼,用於從字符串中去除字母數字字符-更改此字符以從字符串中去除第一連續數字序列的時間不應該太長。

CREATE FUNCTION dbo.UDF_ParseAlphaChars
(
@string VARCHAR(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN
    DECLARE @IncorrectCharLoc SMALLINT
    SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)

    WHILE @IncorrectCharLoc > 0
    BEGIN
        SET @string = STUFF(@string, @IncorrectCharLoc, 1, '')
        SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
    END

    SET @string = @string

    RETURN @string
END
GO

如果您使用的是.NET,則可以使用正則表達式進行抓取:

var input = "ax938477ed1";
var reg = new Regex("[0-9]+");
var match = reg.Match(input);
int number = -1;
if (match.Success)
    number = Convert.ToInt32(match.Groups[0].Value);

這將存儲938477。

可能使用正則表達式是最簡單的。

取決於數據庫-有些具有正則表達式功能-(SQL Server看起來可以將其添加到服務器中未經測試的MSDN文章

否則,您可以使用like來減少查詢。 Sybase允許x之類的'%[0-9]&'查找帶有數字的行,然后在客戶端中使用正則表達式。

我同意為此使用RegEx,假設您使用的是SQL 2005或2008,則可以使用CLR。 這是一些在SQL Server中使用RegEx的UDF代碼,應該會有所幫助:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.Text
Imports System.Text.RegularExpressions
Imports Microsoft.SqlServer.Server

Partial Public Class UserDefinedFunctions

    <Microsoft.SqlServer.Server.SqlFunction()>
    Public Shared Function IsRegexMatch(ByVal input As SqlString, ByVal pattern As SqlString) As SqlBoolean
        If input.IsNull OrElse pattern.IsNull Then Return SqlBoolean.Null
        Return Regex.IsMatch(input.Value, pattern.Value, RegexOptions.IgnorePatternWhitespace Or RegexOptions.Singleline Or RegexOptions.Multiline)
    End Function

    <Microsoft.SqlServer.Server.SqlFunction()>
    Public Shared Function RegexReplace(ByVal input As SqlString, ByVal pattern As SqlString, ByVal replacement As SqlString) As SqlString
        If input.IsNull OrElse pattern.IsNull OrElse replacement.IsNull Then Return SqlString.Null
        Return Regex.Replace(input.Value, pattern.Value, replacement.Value, RegexOptions.IgnorePatternWhitespace Or RegexOptions.Singleline Or RegexOptions.Multiline)
    End Function
End Class

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM