SQL Server 分割字符串转列


CREATE FUNCTION dbo.sf_DS_SplitNVarchar
(
@strValues nvarchar(4000)
)
RETURNS @tblStrList TABLE (id int identity(1,1),value nvarchar(4000))
AS
BEGIN
declare @strTmp nvarchar(4000)
declare @intPos int
select @strValues=ltrim(rtrim(@strValues))

while @strValues<>''
begin
select @intPos=case when charindex(',',@strValues)=0 then len(@strValues) else charindex(',',@strValues)-1 end
select @strTmp=ltrim(rtrim(substring(@strValues,1,@intPos)))
select @strValues=ltrim(rtrim(substring(@strValues,@intPos+2,len(@strValues))))

insert into @tblStrList values(@strTmp)
end

RETURN
END

-- select value from dbo.sf_ds_splitnvarchar('A,B,C')


--【方法二】

CREATE FUNCTION dbo.sf_SplitVarchar_Sign
(
@strValues varchar(8000), --待分割字符串
@Sign char(1) --分割符
)
RETURNS @tblStrList TABLE (Zid int identity(1,1),value varchar(8000))
AS
BEGIN

declare @strTmp varchar(8000),
@intPos int

select @strValues=ltrim(rtrim(@strValues))
if right(@strValues,1) <> @Sign
select @strValues = @strValues + @Sign

if @strValues <> @Sign
begin
select @intPos = charindex(@Sign,@strValues)
while @intPos > 0
begin
select @strTmp = ltrim(rtrim(substring(@strValues,1,@intPos - 1)))
insert into @tblStrList values(@strTmp)
select @strValues = ltrim(rtrim(substring(@strValues,@intPos + 1,len(@strValues))))
select @intPos = charindex(@Sign,@strValues)
select @intPos = isnull(@intPos,0)
end
end

RETURN
END


--select value from dbo.sf_SplitVarchar_Sign('A,B,C',',')

--A
--B
--C

posted @ 2018-01-17 12:05  TuringChang  阅读(588)  评论(0编辑  收藏  举报