日期:2014-05-18  浏览次数:20387 次

更新表的问题:主细表结构,细表中的某一标志字段,如果这个标志字段都为1,那么也要更新主表的标志字段也为1,否则为0
例如:
一个订单下面对应很多订单行
订单对应一个主表,有一个标志字段FlagCompleteH
订单行对应它的细表,有一个标志字段FlagD
一个订单行如果处理完毕,那么要更新这行的FlagCompleteD字段为1,
否则默认是0。
现在要批量更新,把订单行的FlagCompleteD字段都为1的订单,FlagCompleteH更新为1,否则是0

------解决方案--------------------
update 主表 set flagcompleteh=1
from 主表,
(select 主表.主键列,sum(FlagCompleteD) as col1,count(1) as col2
from 主表,从表
where 主表.主键列=从表.主键列
group by 主表.主键列) t
where 主表.主键列=t.主键列 and t.col1=t.col2
------解决方案--------------------
在细表上建个更新触发器
------解决方案--------------------
其实,子表不必要使用标志位置
直接读主表信息就可以了的
------解决方案--------------------
CREATE TRIGGER trig_T_CGDtoJHD ON dbo.T_CGD_TF
after INSERT, UPDATE, DELETE
AS
declare
@NO int, --当前行号
@SumNO int, -- 记录单据总行数
@Sumprd_Count decimal(18,3),--采购数量
@Sumprd_Count_In decimal(18,3),--入库数量
@ParentID varchar(20),
@JHDID varchar(20),
@Parentitem int,
@Item int,
@blnHaveCGD bit --标志是否有采购单

--定义游标,遍梨更新数据
set @NO=0
set @SumNO=(select Count(*) from inserted)

if @sumno> 0--判断是删除还是增加
begin
declare C_CGDTF scroll cursor for (select item,parentid,ParentItem,JHDID from inserted)
end
else
begin
declare C_CGDTF scroll cursor for (select item,parentid,ParentItem,JHDID from deleted)
end
open C_CGDTF
fetch from C_CGDTF into @Item,@parentid,@Parentitem,@JHDID
while @@fetch_status = 0
begin
set @no=@no+1
set @Sumprd_Count=(select sum(prd_count) from t_cgd_tf where JHDID=@JHDID and ParentItem=@ParentItem)
set @Sumprd_Count_In=(select sum(prd_count_In) from t_cgd_tf where JHDID=@JHDID and ParentItem=@ParentItem)
if @Sumprd_Count is null
begin
set @sumprd_count=0
set @blnHaveCGD=0
end
else set @blnHaveCGD=1

if @Sumprd_Count_In is null set @Sumprd_Count_In=0

update t_jhd_tf set prd_count_cg = @Sumprd_Count,prd_count_In=@Sumprd_Count_In,locked=@blnHaveCGD where parentid=@JHDID and item=@ParentItem



fetch from C_CGDTF into @Item,@parentid,@Parentitem,@JHDID
end

update t_jhd_mf set JZBZ=case (select count(*) from t_jhd_tf where Prd_Count <> Prd_Count_CG and parentid=@JHDID) when 0 then 1 else 0 end where nbid=@JHDID

close C_CGDTF
deallocate C_CGDTF

=============================================================================
呵呵,比较懒,这个是我的一个程序里的子表更新主表的标志的触发器,你可以参考一下