sql查询里 怎么拆分字符串(按“/”拆分)

字符串比如是:
a/b/c/d
1/2/3/4
要分列成4行
a b c d
1 2 3 4
和excel的“分列”效果一样
注意是批量处理的 上万条数据 所以希望消耗资源少
求语句 怎么写

先建立一个自定义函数,之个函数非常有用,建议收入自已的数据库
CREATE FUNCTION mysplit--将以某分隔符分段的字串,按指定的顺序号提取子串:  

 (@str nvarchar(2000),--源字串
   @sn int,    --提取序号
   @Deli varchar(1) --分隔符
  )
   RETURNS varchar(100)
AS
BEGIN
declare @first int,@last int,@result varchar(1000),@sn0 int
select @sn0=0,@first=0,@LAST=1,@str=@str+REPLICATE(@DELI,1)
while @sn0!=@sn
 begin
 select @sn0=@sn0+1,@first=@LAST,@last=charindex(@DELI,@str,@LAST)+1
 end
if @last-@first-1<0
set @result=''
else
SET @RESULT=SUBSTRING(@str,@FIRST,@LAST-@FIRST-1)
RETURN ( @RESULT )
END

查询方法:

DECLARE @A VARCHAR(100),@B VARCHAR(100),@C VARCHAR(100)
SELECT 
@A=DBO.MYSPLIT('A|B|C',1,'|') ,
@B=DBO.MYSPLIT('A|B|C',2,'|') ,
@C=DBO.MYSPLIT('A|B|C',3,'|') 
SELECT @A,@B,@C

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-07-27
自定义split函数

CREATE FUNCTION [dbo].[split]
(@str nvarchar(4000),@code varchar(10),@no int )
RETURNS varchar(200)
AS
BEGIN
declare @intLen int
declare @count int
declare @indexb int
declare @indexe int
set @intLen=len(@code)
set @count=0
set @indexb=1
if @no=0
if charindex(@code,@str,@indexb)<>0
return left(@str,charindex(@code,@str,@indexb)-1)
else
return @str
while charindex(@code,@str,@indexb)<>0
begin
set @count=@count+1
if @count=@no
break
set @indexb=@intLen+charindex(@code,@str,@indexb)
end
if @count=@no
begin
set @indexe=@intLen+charindex(@code,@str,@indexb)
if charindex(@code,@str,@indexe)<>0
return substring(@str,charindex(@code,@str,@indexb)+len(@code),charindex(@code,@str,@indexe)-charindex(@code,@str,@indexb)-len(@code))
else
return right(@str,len(@str)-charindex(@code,@str,@indexb)-len(@code)+1)
end
return ''
END本回答被网友采纳
第2个回答  2012-07-27
itjob上有视频看
相似回答