替换为正则表达式

时间:2014-01-28 16:59:26

标签: sql sql-server regex

请参阅下面的SQL语句:

select * from person1
inner join person2 on person1.reference=person2.reference
where replace(person1.surname,' ','')<>replace(person2.surname,' ','')

我想加入引用,然后在person1和person2中列出所有姓氏不同的人。但是,我不希望在匹配中使用空格和某些其他字符,但我不想要这样的嵌套替换语句:

replace(replace(replace(person1.surname,' ',''),char(39),''),'-','')<>replace(replace(replace(person2.surname,' ',''),char(39),''), '-','')

我正在尝试设计一个SQL语句,将以下列表中不包含的所有字符替换为零长度字符串:

A-Z
a-z
Hyphen

我相信我可以使用正则表达式解决这个问题。

2 个答案:

答案 0 :(得分:3)

就像我说的那样,这将和树木生长一样快,但玩得开心......

CREATE FUNCTION dbo.StripBadCharacters
(
  @input NVARCHAR(255)
)
RETURNS NVARCHAR(255)
WITH SCHEMABINDING
AS
BEGIN
  DECLARE @s NVARCHAR(255), @i INT;

  SELECT @s = N'', @i = 0;
  WHILE @i <= LEN(@input)
  BEGIN
    IF SUBSTRING(@input, @i, 1) LIKE N'[A-Za-z-]'
    BEGIN
      SET @s = @s + SUBSTRING(@input, @i, 1);
    END
    SET @i = @i + 1;
  END

  RETURN (@s);
END
GO

样本用法:

DECLARE @x TABLE(name1 NVARCHAR(255), name2 NVARCHAR(255));

INSERT @x VALUES('bob o''brien', 'bob obrien'); -- this will return
INSERT @x VALUES('bob obrien', 'bob o '' brien'); -- this will return
INSERT @x VALUES('bob o''brien', 'bob o''brian'); -- this will not

SELECT name1, name2 FROM @x 
  WHERE dbo.StripBadCharacters(name1) = dbo.StripBadCharacters(name2);

答案 1 :(得分:0)

内联表值函数。这是相对活泼的。

CREATE FUNCTION dbo.StringCompareAlpha(
  @str1 nvarchar(255), 
  @str2 nvarchar(255)
)
RETURNS TABLE AS
RETURN
( 
  WITH
    t0 AS (SELECT 0 i UNION ALL SELECT 0),
    t1 AS (SELECT 0 i FROM t0 a, t0 b),
    t2 AS (SELECT 0 i FROM t1 a, t1 b),
    t3 AS (SELECT 0 i FROM t2 a, t2 b),
    n  AS (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 0)) i FROM t3),
    s1 AS (SELECT ROW_NUMBER() OVER(ORDER BY i) i, SUBSTRING(@str1,i,1) c FROM n WHERE SUBSTRING(@str1,i,1) LIKE '[A-Za-z-]' AND i <= LEN(@str1)),
    s2 AS (SELECT ROW_NUMBER() OVER(ORDER BY i) i, SUBSTRING(@str2,i,1) c FROM n WHERE SUBSTRING(@str2,i,1) LIKE '[A-Za-z-]' AND i <= LEN(@str2))
  SELECT 1 i WHERE NOT EXISTS(
    (SELECT * FROM s1 EXCEPT SELECT * FROM s2)
    UNION ALL
    (SELECT * FROM s2 EXCEPT SELECT * FROM s1)
  )
)
GO 

DECLARE @x TABLE(name1 NVARCHAR(255), name2 NVARCHAR(255));

INSERT @x VALUES('bob o''brien', 'bob obrien'); -- this will return
INSERT @x VALUES('bob obrien', 'bob o '' brien'); -- this will return
INSERT @x VALUES('bob o''brien', 'bob o''brian'); -- this will not

SELECT * FROM @x CROSS APPLY dbo.StringCompareAlpha(name1,name2)