sql存储过程处理数组参数
我的存储过程传入一个参数,格式是这样:str1,0,0,0,0|str2,0,0,0,0|str3,0,0,0,0|str4,0,0,0,0要实现把每个|分割的字段插入一...
我的存储过程传入一个参数,格式是这样:
str1,0,0,0,0|str2,0,0,0,0|str3,0,0,0,0| str4,0,0,0,0
要实现把每个 | 分割的字段插入一张表的每个字段,结果是这样
name a1 a2 a3 a4
str1 0 0 0 0
str2 0 0 0 0
str3 0 0 0 0
请教高人赐教! 展开
str1,0,0,0,0|str2,0,0,0,0|str3,0,0,0,0| str4,0,0,0,0
要实现把每个 | 分割的字段插入一张表的每个字段,结果是这样
name a1 a2 a3 a4
str1 0 0 0 0
str2 0 0 0 0
str3 0 0 0 0
请教高人赐教! 展开
2个回答
展开全部
declare @str varchar(500)
declare @insert varchar(8000)
select @insert = 'insert into youTable values '
select @str='str1,1,1,1,1|str2,2,2,2,2|str3,3,3,3,5|str4,4,4,45,4'
select @str=@insert+'('''+@str+''')'
select @str = REPLACE(@str,',',''',''')
select @str = REPLACE(@str,'|',''') '+CHAR(13)+@insert+'(''')
print @str
--exec(@str) 动态执行下生成的语句就好了
--print 结果如下:
insert into youTable values ('str1','1','1','1','1')
insert into youTable values ('str2','2','2','2','2')
insert into youTable values ('str3','3','3','3','5')
insert into youTable values ('str4','4','4','45','4')
展开全部
--方法一,用字符串替换和拼接,构造成insert into 表 Select 的样子,然后执行
--方法二,用字符串拆分
Declare @A varchar(800)='str1,0,0,0|str2,0,0,0|str3,0,0,0'
Set @A='Insert into T Select '''+@A
Set @A=replace(REPLACE(@A,'|',''' union all select '''),',',''',''')+''''
Exec(@A)
/*
Insert into T
Select 'str1','0','0','0'
union all
select 'str2','0','0','0'
union all
select 'str3','0','0','0'
*/
--方法二,用字符串拆分
Declare @A varchar(800)='str1,0,0,0|str2,0,0,0|str3,0,0,0'
Set @A='Insert into T Select '''+@A
Set @A=replace(REPLACE(@A,'|',''' union all select '''),',',''',''')+''''
Exec(@A)
/*
Insert into T
Select 'str1','0','0','0'
union all
select 'str2','0','0','0'
union all
select 'str3','0','0','0'
*/
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询