今天在编写一个脚本时,正巧遇到一个有规则字符串需要转化成表,于是就动手写了个函数。在此献丑。。。。
--www.naoqiu.com
--获取库存关系表(格式:'1:20,3:10,55:230')
returns @tem table( id int,num int)
as
begin
declare @index int,@index_child int
set @index=CHARINDEX(',',@txt)
--循环n-1项
while @index>0 begin
set @index_child=CHARINDEX(':',SUBSTRING(@txt,1,@index))
insert into @tem select SUBSTRING(@txt,1,@index_child-1),
SUBSTRING(@txt,@index_child+1,@index-@index_child-1)
set @txt=SUBSTRING(@txt,@index+1,LEN(@txt)-@index)
set @index=CHARINDEX(',',@txt)
end
--插入最后一项
if LEN(@txt)>0 begin
set @index_child=CHARINDEX(':',@txt)
insert into @tem select SUBSTRING(@txt,1,@index_child-1),
SUBSTRING(@txt,@index_child+1,LEN(@txt)-@index_child)
end
return
end
go
这个函数行分隔符",",列分割符“:”,在这个函数中是固定死,可以改成参数传递,就更加灵巧。我在此抛砖引玉
更多源代码尽在脑球源代码 http://download.naoqiu.com