今天在编写脚本时发现需要过滤首尾特定“,”特定字符,而ms sql 没有提供类似c#方便过滤首尾特定字符,不得不自己编写个函数以方便自己操作需要,现在把函数与大家分享。 --过滤首字符
create function Trim_Left(@txt nvarchar(2000), @c nchar(1)) returns nvarchar(2000) as begin declare @length int --判断首字符是否存在所要替换的字符 while LEFT(@txt,1)=@c begin set @length= len(@txt) if @length=1 begin return '' end set @txt=substring(@txt,2,@length-1) end return @txt end go
--过滤末尾字符
create function Trim_Right(@txt nvarchar(2000), @c nchar(1)) returns nvarchar(2000) as begin --判断首字符是否存在所要替换的字符 while right(@txt,1)=@c begin set @txt=substring(@txt,1,len(@txt)-1) end return @txt end go --过滤首尾字符
Create function Trim(@txt nvarchar(2000), @c nchar(1)) returns nvarchar(2000) as begin set @txt=dbo.Trim_left(@txt,@c) if len(@txt)>0 begin set @txt=dbo.Trim_Right(@txt,@c) end return @txt end go
测试:
--过滤脑球生活资讯平台空格 select dbo.Trim_Left(' http://www.naoqiu.com/',' ') --过滤脑球生活资讯平台尾巴的/ select dbo.Trim_Right('http://www.naoqiu.com/','/')