前一段時間我使用下面的解決了這個問題功能
create function dbo.[fnrReplacetor](@strtext varchar(2000))
returns varchar(2000)
as
begin
declare @i int = 32, @rplc varchar(1) = '';
while @i < 256
begin
if (@i < 48 or @i > 57) and CHARINDEX(char(@i),@strtext) > 0
begin
--° #176 ~ 0 --¹ #185 ~ 1 --² #178 ~ 2 --³ #179 ~ 3
set @rplc = case @i
when 176 then '0'
when 185 then '1'
when 178 then '2'
when 179 then '3'
else '' end;
set @strtext = REPLACE(@strtext,CHAR(@i),@rplc);
end
set @i = @i + 1;
end
return @strtext;
end
GO
select dbo.[fnrReplacetor]('12345/97')
請注意,生病時也要考慮字符°,1,2,數字,然後用0,1,2,3替換。
我把它放在一個函數中,以便在我的場景中重複使用它,我需要一次修復很多表中的許多列。
update t
set t.myColumn = dbo.[fnrReplacetor](tempdb.myColumn)
from test t
where tempdb.myColumn is not null
或只是
select dbo.[fnrReplacetor](tempdb.myColumn) as [Only Digits]
from test t
where tempdb.myColumn is not null
觀測數據:這是不是一個徹底的一個fatest方式。
編輯
非UDF解決方案必須使用REPLACE
但由於正則表達式是不是很大的SQL就可以結束做一些討厭的,如下面的例子:
declare @test as table (myColumn varchar(50))
insert into @test values ('123/45'),('123-4.5')
Select replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(myColumn,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z',''),'.',''),'-',''),'/','')
from @test
SQL Server沒有任何內置的正則表達式替換支持。如果您確實需要這樣做,您可能必須使用UDF。 –
有各種類型的[一堆解決方法](https://stackoverflow.com/questions/18625548/t-sql-select-query-to-remove-non-numeric-characters)。 –
看看這個https://stackoverflow.com/questions/1007697/how-to-strip-all-non-alphabetic-characters-from-string-in-sql-server – RealCheeseLord