日期:2014-05-17 浏览次数:20532 次
--创建测试表
if OBJECT_ID('tb')>0 drop table tb
go
select top 0 1 id,cast('name' as varchar(50)) as name into tb
GO
--创建过程
if OBJECT_ID('p_InsStr','p')>0 drop proc p_InsStr
go
create proc p_InsStr
@insertStr varchar(1000)
as
--没有过滤防攻击代码,需要的话自己参考相关资料加入
set nocount on
set @insertStr=LTRIM(RTRIM(@insertStr))
if left(@insertStr,1)=',' set @insertStr=stuff(@insertStr,1,1,'')
if RIGHT(@insertStr,1)<>',' set @insertStr=@insertStr+','
declare @i int
set @i=0
while LEN(@insertStr)>0
begin
set @i=@i+1
insert tb select @i,LEFT(@insertStr,CHARINDEX(',',@insertStr)-1)
set @insertStr=STUFF(@insertStr,1,CHARINDEX(',',@insertStr),'')
end
GO
--测试结果
exec p_InsStr 'a,b,c'
exec p_InsStr ',d,e,tony,'
select * from tb
/*
id name
----------- --------------------------------------------------
1 a
2 b
3 c
1 d
2 e
3 tony
(6 行受影响)
*/