使用TRIGGER在DELETE之前将已删除的记录插入历史表中

时间:2013-03-07 14:29:41

标签: asp.net

我有一个gridview,它显示表中的记录集 - Master2。我想使用gridview删除此表中的记录。在删除发生之前,我想将记录插入到历史表中,其中包含来自执行删除操作的人的datetimestamp和userid。这是可能的还是我应该用一系列下拉框和一个按钮构建字段?

3 个答案:

答案 0 :(得分:1)

  

使用FOR DELETE触发器:

CREATE TRIGGER TriggerName    
ON TableName  
FOR DELETE    
AS     
BEGIN    
    INSERT INTO HistoryTable(Col1, Col2, Col3)  
    SELECT Col1, GETDATE(), Col3  
    FROM TableName  
    WHERE DeletedRecordID IN (SELECT DeletedRecordID FROM TableName)     
END  

答案 1 :(得分:0)

使用触发器。

更安全,这意味着每次从该历史记录表中删除记录时(无论机制如何),它仍然会触发。

代码也更容易,因为您不必在.net代码中放置任何内容来处理它。

最后,由于涉及的网络流量为零,因此速度更快。

答案 2 :(得分:0)

我建议使用标记进行删除,而不是实际删除记录... 在gridview中,你添加了一个额外的检查点,当它被选中时它会触发......就像这样

<asp:TemplateField HeaderText="Delete" SortExpression="ToBeDeleted">
                            <EditItemTemplate>
                                <asp:TextBox ID="txtToBeDeleted" runat="server" Text='<%# Bind("ToBeDeleted") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <%--<asp:Label ID="lblToBeDeleted" Width="20px" runat="server" Text='<%# Bind("ToBeDeleted") %>'></asp:Label>--%>
                                <asp:CheckBox ID="chkToBeDeleted" Width="20px" runat="server" Checked='<%# Bind("ToBeDeleted") %>' OnCheckedChanged="chkToBeDeleted_CheckedChanged" AutoPostBack="true"/>
                            </ItemTemplate>
                            <ItemStyle CssClass="overflowClass" HorizontalAlign="Center" Wrap="false" />
                        </asp:TemplateField>

然后在后面的代码中处理触发器:

protected void chkToBeDeleted_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridViewRow gvr = (GridViewRow)cb.NamingContainer;
            int id = (int)gvWines.DataKeys[gvr.RowIndex].Value;

            ListOfWine record = (from l in db.ListOfWines
                         where l.Id == id
                         select l).FirstOrDefault();

            //here you add the record to another table and then continue flagging the record for deletion

         record.ToBeDeleted = cb.Checked;
db.SaveChanges();
            gvWines.DataBind();
        }
相关问题