|
|
#6
mywisdom882017-11-07 16:26
-- 测试数据
if object_id('tempdb..#子表名称') is not null drop table #子表名称
create table #子表名称(姓名 varchar(10),津贴 numeric(10,2),金额 numeric(10,2))
insert into #子表名称(姓名,津贴,金额)
select '张三',53,5003 union all
select '李四',54,5004 union all
select '王五',55,5005 union all
select '陈七',57,5007
-- select * from #子表名称
-- 开始
declare @lcxm varchar(1000),@lcjt varchar(1000),@lcje varchar(1000)
declare @xm varchar(200),@jt varchar(200),@je varchar(200),@num_xm int,@i1 int,@i2 int,@i3 int
-- @lcxm 要用","结尾
select @lcxm='张三,李四,王五,赵六,陈七,',@lcjt='53,54,55,56,57,',@lcje='5003,5004,5005,5006,5007,',@num_xm=0,@i1=0,@i2=0,@i3=0
if object_id('tempdb..#v_xm') is not null drop table #v_xm
select * into #v_xm from #子表名称
set @i1=charindex(',',@lcxm)
set @i2=charindex(',',@lcjt)
set @i3=charindex(',',@lcje)
while @i1>1
begin
select @xm=substring(@lcxm,1,@i1-1),@jt=substring(@lcjt,1,@i2-1),@je=substring(@lcje,1,@i3-1)
select @lcxm=substring(@lcxm,@i1+1,len(@lcxm)-@i1),@lcjt=substring(@lcjt,@i2+1,len(@lcjt)-@i2),@lcje=substring(@lcje,@i3+1,len(@lcje)-@i3)
set @i1=charindex(',',@lcxm)
set @i2=charindex(',',@lcjt)
set @i3=charindex(',',@lcje)
if exists(select 姓名 from #v_xm where 姓名=@xm)
begin
update #v_xm set 金额=金额+@je where 姓名=@xm
set @num_xm=@num_xm+1
end
else
begin
insert into #v_xm(姓名,津贴,金额) values(@xm,@jt,@je)
end
end
-- 结束
-- 查看结果
select * from #子表名称
select * from #v_xm
|