sql如何分割字段的一串数字?
比如我表A里有个字段B,数据为1234,
要的就是一段sql 查询出表A中B字段结果为 1,2,3,4
[解决办法]
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<=@l) 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 行受影响)
[解决办法]
--> 测试数据: #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*/