Lee*_*ett 9 sql t-sql sql-server
有没有办法从SQL服务器中的字符串/字段中删除特殊字符(只留下字母数字)而没有循环/自定义函数?
到目前为止,我提出的最好的是:
Create Function [dbo].[strip_special](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
While PatIndex('%[^a-z0-9]%', @Temp) > 0
Set @Temp = Stuff(@Temp, PatIndex('%[^a-z0-9]%', @Temp), 1, '')
Return @TEmp
End
Run Code Online (Sandbox Code Playgroud)
在某些服务器上,我没有创建用户定义函数的权限,所以我希望能够在没有的情况下实现相同的结果.我也担心循环的效率/性能(虽然我猜即使内置函数/方法本身也可能使用循环).
谢谢
我假设你有一个你想要替换的列,这是你可以这样做的:
declare @table table(id int, temp varchar(15))
insert @table values(1, 'abc-.123+')
insert @table values(2, '¤%&(abc-.?=&(/#')
;with t1 as
(
select temp a, id from @table
union all
select cast(replace(a, substring(a, PatIndex('%[^a-z0-9]%', a), 1), '') as varchar(15)), id
from t1
where PatIndex('%[^a-z0-9]%', a) > 0
)
select t2.*, t1.a from t1
join @table t2
on t1.id = t2.id
where PatIndex('%[^a-z0-9]%', a) = 0
option (maxrecursion 0)
Run Code Online (Sandbox Code Playgroud)
结果:
id temp a
----------- --------------- ---------------
2 ¤%&(abc-.?=&(/# abc
1 abc-.123+ abc123
Run Code Online (Sandbox Code Playgroud)