使用Sql查询进行正则表达式

时间:2016-06-20 09:36:34

标签: sql sql-server regex

  

选择a。[PREMISES],a。[Class] FROM [Legacy]。[dbo]。[MyTables] as a;

以上查询返回:

enter image description here

您能告诉我如何从查询列210,中删除211,a.[Class]吗?

注意:我刚刚举了一个例子。我需要一个通用的解决方案,它将适用于a.[Class]列的所有行。

注2: Class列的格式如下所示。numeric然后,之后的string。我需要先删除2部分。只需保留string部分。

4 个答案:

答案 0 :(得分:2)

你不一定需要在这里使用正则表达式。您可以尝试使用REPLACE

SELECT  a.[PREMISES],
        REPLACE(REPLACE(a.[Class],'210, ',''),'211, ','') as [Class] 
FROM [Legacy].[dbo].[MyTables] as a;

要在第一个,之前删除所有内容:

SELECT  a.[PREMISES],
        LTRIM(RIGHT(NULLIF(a.[Class],''),LEN(a.[Class])-CHARINDEX(',',a.[Class]))) as [Class]
FROM [Legacy].[dbo].[MyTables] as a;

此查询,针对该数据

PREMISES            Class
Victoria Ln         210, Single Family (no style specified)
West 10th Street    211, Ranch, Single Family
East 2nd Street     Single Family

会给你这个输出:

PREMISES            Class
Victoria Ln         Single Family (no style specified)
West 10th Street    Ranch, Single Family
East 2nd Street     Single Family

答案 1 :(得分:2)

您可以使用以下查询从,开始返回结果。

SELECT  a.[PREMISES],
        SUBSTRING(a.[Class], CHARINDEX(',',a.[Class]) + 1, LEN(a.[Class])) as [Class] 
FROM [Legacy].[dbo].[MyTables] as a;

答案 2 :(得分:0)

只需从字符串中删除所有数字字符。

SELECT a.[PREMISES],
    SUBSTRING(a[Class], PATINDEX('%[a-z]%', a.[Class]), LEN(a.[Class])) 
  FROM [Legacy].[dbo].[MyTables] a

答案 3 :(得分:0)

试试这个:

CREATE FUNCTION Fun_Refiner ( @val VARCHAR(MAX) )
RETURNS VARCHAR(MAX)
AS
BEGIN
    WHILE 1 = 1
        BEGIN
            IF PATINDEX('[0-9]%', @val) > 0 OR SUBSTRING(@val, 1, 1) = ','
                SET @val = RTRIM(LTRIM(REPLACE(@val,SUBSTRING(@val,PATINDEX('[0-9,]%',@val), 1), '')));
            ELSE
                BREAK;
        END;
      RETURN @val
END;

就这样称呼它:

SELECT a.[Class], dbo.Fun_Refiner(a.[Class]) FROM YourTable AS a