现在高版本的Sql Server都是有系统的内置函数进行拆分合合并字符串的,但是有些客户用的Sql Server版本较旧,而你又要用到拼接或拆分字符串的时候就需要自己来写函数进行操作了,下面直接放函数
拆分
IF exists(SELECT * FROM sysobjects WHERE name='f_split' and Type='FN')
DROP FUNCTION [dbo].[f_split]
Go
Create function [dbo].[f_split](@SourceSql varchar(8000),@StrSeprate varchar(10))
returns @temp table(Item varchar(100))
--实现split功能的函数
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>''
insert @temp values(@SourceSql)
return
end
GO
拼接
IF exists(SELECT * FROM sysobjects WHERE name='PraisedDepJoinStr' and Type='FN')
DROP FUNCTION [dbo].[PraisedDepJoinStr]
Go
Create Function PraisedDepJoinStr(@SNO as varchar(20))
returns varchar(200)
as
begin
declare @s as varchar(8000)
set @s=''
select @s=@s+','+ltrim(rtrim(DepID)) from (select DepID from hcrmPraiseDep where praiseid=@SNO)A
set @s=stuff(@s,1,1,'')
return @s
end
go
网友评论