繁体   English   中英

对于SQL中我的用户表的每个列值更改,将记录插入到事务表中

[英]Insert record into transaction table for each column value change of my user table in SQL

我有一个包含数据的用户表

User_Name
User_Address
User_Gender 

等等..

现在我的交易表包含如下字段:

Trans_Id
Trans_User_Field
Trans_Previuos_Data
Trans_Add_Date

现在在我的ASP.net应用程序中,当用户更新其地址或名称或页面上的任何其他字段时,我必须将其与USer表进行比较,并将每个更新的字段/列的记录与以前的数据一起插入事务表中。

在这里,Trans_User_field会为您提供更新的字段(User_Name,User_Address,User_Gender)

请告诉我什么是最好的方法。 在SQL端或应用程序端执行此操作。

谢谢

尽管我可能对此感到满意,但是由于人们强烈讨厌触发器,因此我将在这里建议一个。 您可以这样构建一个:

CREATE TRIGGER update_user ON table FOR UPDATE
AS

DECLARE @update_mask AS INT
SELECT @update_mask = COLUMNS_UPDATED()

IF ( @update_mask & 1 = 1 ) -- this means the first column was modified
IF ( @update_mask & 2 = 2 ) -- this means the second column was modified
IF ( @update_mask & 4 = 4 ) -- this means the third column was modified
IF ( @update_mask & 8 = 8 ) -- this means the fourth column was modified

我想你明白了。 在这里,您可以从updated行中获取更新的值,然后将其INSERT到其他表中。 请参阅,使用COLUMNS_UPDATED方法可以为您带来真正的灵活性。 您可以通过将列的位值相加并查找来轻松确定是否修改了一列。 假设我想知道住址和性别是否都发生了更改(无论出于何种原因),我可以这样做:

IF ( @update_mask & 6 = 6 ) -- both the second the third fields were modified

如何尝试另一种方法。 创建一个Trans_User表将把User表和Trans_Date中的所有字段。 然后在User表上创建插入/更新/删除触发器,以使用先前的数据填充Trans_User表。 看一下这个问题这篇代码项目文章。

假设您正在使用ASP.NET Web窗体。

在您的.aspx页面中

 TextBox1: <asp:TextBox runat="server" id="TextBox1" /><br />
 TextBox2: <asp:TextBox runat="server" id="TextBox2" /><br />
 <asp:Button runat="server" id="Button1" OnClick="Button1_Click" Text="Submit" />

在您的.aspx.cs页面中

 protected void Button1_Click(object sender, EventArgs e)
 {
      string original_text=GetOriginalTextOfTextBox1();
      if(TextBox1.Text==original_text)
      {
           //the text didn't change
      }
      else
      {
           //the text changed. need to update the transaction table and the user table.
      }
      string originaltext2=GetOriginalTextOfTextBox2();
      if(TextBox2.Text==originaltext2)
      {
           //the text didn't change
      }
      else
      {
           //the text changed. need to update the transaction table and the user table.
      }

 }
 protected string GetOriginalTextOfTextBox1()
 {
     //code here that gets the original value of TextBox1 from the User table.
 }
 protected string GetOriginalTextOfTextBox2()
 {
      //code here that gets the original value of TextBox2 from the User table.
 }

}

一旦有了概念,您可能希望将所有这些使用集合(列表)和强类型对象组合在一起。 这将最大程度地减少对数据库的调用次数,并简化您的代码。

-编辑-如果要使用交易记录中的单个记录存储单个更新的所有历史记录,则需要修改事务处理表以一次支持所有字段。 请注意,这可能不那么节省空间,具体取决于您希望用户更新每个事务中的多个字段还是仅更新一个字段。

 Trans_Id
 User_Name
 User_Gender
 User_Address
 Trans_Add_Date

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM