我传给存储过程一个字符串
格式为:1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1,n:n:n:n,规律是4个整数一个段,整数间为“:”分隔,段之间用“,”分隔
我想实现以下的效果
先把字符串以“,”为分隔符进行拆分
拆分后每段字符的4个整数分别按顺序放到某个表(例如mytable)中的A,B,C,D四个字段中例如执行后mytable中是这样
A B C D1 2 3 4
0 2 6 2
34 3 1 1
9 1 1 1
...这样的存储过程应该如何实现
格式为:1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1,n:n:n:n,规律是4个整数一个段,整数间为“:”分隔,段之间用“,”分隔
我想实现以下的效果
先把字符串以“,”为分隔符进行拆分
拆分后每段字符的4个整数分别按顺序放到某个表(例如mytable)中的A,B,C,D四个字段中例如执行后mytable中是这样
A B C D1 2 3 4
0 2 6 2
34 3 1 1
9 1 1 1
...这样的存储过程应该如何实现
参考
Set @temp=@MyVarchar
while @temp<>''
begin
@temp1=SUBSTRING(@temp,0,CHARINDX(',',@temp))--取得了第一个四数字数组了。 --中间处理同理 @temp=SUBSTRING(@temp,CHARINDX(',',@temp),Len(@temp))end
alter Proc Test
( @str varchar(200)
)
as
begin
create table Test_Table(A int not null,B int not null,C int not null,D int not null)
declare @i int
declare @j int
declare @k int
declare @l int
declare @s varchar(50)
declare @sql varchar(200)
set @i=0
while(@i <> 1)
begin
set @j = charindex(',','1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1,',@i)
if(@j <>0)
begin
set @s = substring('1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1,',@i,@j-@i)
set @sql= 'insert into Test_Table values(' + replace(@s,':',',') + ')'
exec(@sql)
end
set @i = @j+1
end
select * from Test_Table
drop table Test_Table
endexec Test '1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1,'
( @str varchar(200)
)
as
begin
create table Test_Table(A int not null,B int not null,C int not null,D int not null)
declare @i int
declare @j int
declare @k int
declare @l int
declare @s varchar(50)
declare @sql varchar(200)
set @i=0
while(@i <> 1)
begin
set @j = charindex(',',@str,@i)
if(@j <>0)
begin
set @s = substring(@str,@i,@j-@i)
set @sql= 'insert into Test_Table values(' + replace(@s,':',',') + ')'
exec(@sql)
end
set @i = @j+1
end
select * from Test_Table
drop table Test_Table
endexec Test '1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1,'
SELECT
A = T.c.value('(c/text())[1]', 'varchar(10)'),
B = T.c.value('(c/text())[2]', 'varchar(10)'),
C = T.c.value('(c/text())[3]', 'varchar(10)'),
D = T.c.value('(c/text())[4]', 'varchar(10)')
FROM(
SELECT
value = CONVERT(xml,
'<r><c>'
+ REPLACE(
REPLACE(
'1:2:3:4,0:2:6:2,34:3:1:1,9:1:1:1',
':',
'</c><c>'
),
',',
'</c></r><r><c>'
)
+ '</c></r>'
)
)A
CROSS APPLY A.value.nodes('/r') T(c)
(天行健) 非常非常感谢你