+1 @Nico,我需要一个可以从字符串中删除特殊章程的函数,所以我稍微调整了你的函数以便能够做到这一点:
select dbo.PatReplaceAll('St. Martin`n tr‘an, or – in - the * field007', '[^0-9A-Z ]', '')
--Returns 'St Martinn tran or in the field007'
这是功能:
CREATE FUNCTION dbo.PatReplaceAll
(
@Source varchar(8000),
@Pattern varchar( 50),
@Replace varchar( 100)
)
RETURNS varchar(8000)
AS
BEGIN
if @Source is null or @Pattern is null or @Replace is null
return null
if PATINDEX('%' + @Pattern + '%', @Source) = 0
return @Source
-- Declare the return variable here
DECLARE @Result varchar(8000) SET @Result = ''
-- The remainder of the @Source to work on
DECLARE @Remainder varchar(8000) SET @Remainder = @Source
DECLARE @Idx INT
WHILE (LEN(@Remainder) > 0)
BEGIN
SET @Idx = PATINDEX('%' + @Pattern + '%', @Remainder)
IF @Idx = 0 --no match - return
BEGIN
SET @Result = @Result + @Remainder
BREAK
END
-- Concatenate characters before the match to the result
SET @Result = @Result + SUBSTRING(@Remainder, 1, @Idx - 1)
-- Adjust the remainder
SET @Remainder = SUBSTRING(@Remainder, @Idx, LEN(@Remainder) + 1 - @Idx)
SET @Idx = 1
-- Find the last char of the pattern (aka its length)
WHILE PATINDEX(@Pattern, SUBSTRING(@Remainder, 1, @Idx)) = 0
SET @Idx = @Idx + 1
--remove the pattern from the remainder
SET @Remainder = SUBSTRING(@Remainder, @Idx + 1, LEN(@Remainder) - @Idx)
--Add the replace string
SET @Result = @Result + @Replace
END
return @Result
END
GO