在SQL Server 2008中插入触发器之后

时间:2018-04-21 08:44:13

标签: sql sql-server

我有这些表格:

  • TableParent(id,name,paidamt,gstamt)
  • TableChild(id,parentid,paidamt,gstamt)

在具有相同byte[] bytesP7m =out.toByteArray(); File tmpf=new File(Folium.getProperty(session, Folium.GLOBAL_LOCAL_PATH)+File.separator+"error"+File.separator+"error.xml"); FileUtils.writeByteArrayToFile(tmpf, bytesP7m); //BufferedReader br=new BufferedReader(new FileReader(tmpf.getName())); FileInputStream fileIS = new FileInputStream(tmpf); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(fileIS); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "//errori"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); for (int i=0; i<nodeList.getLength(); i++) { //String node=nodeList.item(i).getNodeValue(); returnError=returnError+"\r\n"+nodeList.item(i).getNodeValue(); } 的子表中插入记录后:

parentid

我尝试了这个查询,但它没有工作......

update tableparent(paidamt, gstamt) 
values (sum(TableChild.paidamt), sum(TableChild.gstamt)) 
where  TableChild.parentid =  TableParent.id 
  

**这就是我想要的...... **谢谢,大家支持

CREATE TRIGGER UpdateValueInExpance 
ON ExpPaymentRecipt 
AFTER INSERT
AS
BEGIN  
    DECLARE @pid INT;

    SELECT @pid = id FROM inserted

    DECLARE @tbl TABLE (tds MONEY, amt MONEY)

    INSERT INTO @tbl (tds, amt) 
        SELECT TDS, AmountPaid 
        FROM ExpPaymentRecipt 
        WHERE ExpPaymentRecipt.EID = pid;

    UPDATE Expanses 
    SET PaidAmt = SUM(@tbl.amt),  
        TDSAmt = SUM(@tbl.tds) 
    FROM @tbl 
    WHERE Expanses.id = pid
END

2 个答案:

答案 0 :(得分:0)

这可以使用触发器完成:

在此处阅读有关触发器的信息:triggers

提示:在子表上使用AFTER INSERT触发器

答案 1 :(得分:0)

根据您问题的 description ,您的触发器应如下所示:

CREATE TRIGGER UpdateValueInExpance ON ExpPaymentRecipt  AFTER INSERT
AS BEGIN  
    UPDATE p
        SET gstamt = gstamt + child_paidamt
        FROM tableparent p JOIN
             (SELECT i.parentid, SUM(c.paidamt) as child_paidamt
              FROM inserted i
              GROUP BY i.parentid
             ) c
             ON c.parentid = p.id;
END;

目前还不清楚这与您的示例代码有何关系,因为示例代码与您的定义完全不同(表的名称不同,您设置了两列等)。

假设inserted只有一行,你会犯一个基本错误。这是一个很大的错误,会导致代码中的错误。