CREATE PROCEDURE dbo.UpdateBrowserData
@browserType varchar(200), --定义须查询的字符串 (浏览器类型)
@counter varchar(200) --定义须查询的字符串 (浏览器计数)
as
declare @type varchar(50) --截取出来的浏览器类型
declare @count int --截取出来的浏览器计数
declare @browPos int --定义分隔符','的位置 (针对浏览器类型截取来用的)
declare @browLen int --定义截取出来的子字符串的长度 (针对浏览器类型截取来用的)
declare @countPos int --定义分隔符','的位置 (针对浏览器计数来用的)
declare @countLen int --定义截取出来的子字符串的长度 (针对浏览器计数来用的)
set @browPos=Charindex(',',@browserType,0) --Charindex(分隔符,被查询的字符串,查询起始位置),这里是取分隔符','出现的位置
set @countPos=Charindex(',',@counter,0)
while(@browPos>0)
begin
set @type=Substring(@browserType,0,@browPos) --Substring(被查询的字符串,起始位置,截止位置),根据分隔符的位置截取字符串
set @count= cast(Substring(@counter,0,@countPos) as int)
set @browLen=len(@type) --len(子字符串),取得子字符串的长度
set @countLen=Len(@count)
IF((select count(browserType) from tbBrowser WHERE browserType = @type)= 0) --判断是否已经存在这种类型
BEGIN
insert into tbBrowser ([browserType],[count]) values (@type,@count)--不存在就写入
END
ELSE
BEGIN
update tbBrowser set [count]= @count where [browserType] = @type --存在就更新数据
END
select @type --输出测试来用
select @count --输出测试来用
set @browserType=Stuff(@browserType,1,@browLen+1,'') --Stuff(被查询的字符串,起始位置,截止位置),把子字符串从被查询的字符串中去除
set @counter=Stuff(@counter,1,@countLen+1,'')
set @countPos=Charindex(',',@counter,0)
set @browPos=Charindex(',',@browserType,0) --控制循环的条件
end
go
exec UpdateBrowserData 'IE4,IE5,IE6,', '0,1,2,'
最后需要注意的是 这句exec UpdateBrowserData 'IE4,IE5,IE6,', '0,1,2,' 传递的参数要一一对应,逗号分隔符是字符串的最后一位。