当前位置: 代码迷 >> Sql Server >> sql怎么分割字段的一串数字
  详细解决方案

sql怎么分割字段的一串数字

热度:69   发布时间:2016-04-27 12:07:20.0
sql如何分割字段的一串数字?


比如我表A里有个字段B,数据为1234,



要的就是一段sql 查询出表A中B字段结果为 1,2,3,4


------解决方案--------------------
SQL code
alter function fn_getStr(@v int)returns varchar(32)begin    declare @retValue varchar(32)    set @retValue =''    if (@v is not null)        begin                declare @s varchar(16),                                @l tinyint,                @i tinyint        set @i = 1        set @s =convert(varchar(16),@v)        set @l = len(@s)        while(@i<[email protected])        begin            set @retValue = @retValue + substring(@s,@i,1)+','            --print @retValue            set @i = @i + 1        end    end    return left(@retValue,len(@retValue)-1)endselect dbo.fn_getStr(123)--------------------------------1,2,3,4(1 行受影响)
------解决方案--------------------
SQL code
--> 测试数据: #tbif object_id('tempdb.dbo.#tb') is not null drop table #tbcreate table #tb ([val] varchar(10))set nocount oninsert into #tbselect '1234'declare @Num table(id int)insert into @Num select number from master..spt_values where number between 1 and 100 and type='p'set nocount offdeclare @str varchar(100)select @str=isnull(@str+','+element,element) from (select SUBSTRING(val,id,1) element from #tb a join @Num b on SUBSTRING(val,id,1)<>'') as T print(@str)--结果/*1,2,3,4*/
  相关解决方案