将记录插入到事务表中,以便在SQL中对我的用户表的每个列值进行更改

时间:2013-06-04 19:54:16

标签: c# asp.net 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端或应用程序端执行此操作。

感谢

3 个答案:

答案 0 :(得分:1)

虽然我可能因此而感到厌恶,因为人们激烈地讨厌触发器,我会在这里建议一个。你可以像这样构建一个:

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方法为您提供了一些真正的灵活性。您可以通过将列值添加到一起并仅查找它来轻松确定是否修改了 set 列。所以,假设我想知道地址和性别是否都发生了变化 - 无论出于何种原因 - 我可以这样做:

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

答案 1 :(得分:1)

尝试替代方法怎么样?创建Trans_User表将显示User表和Trans_Date中的所有字段。然后在User表上创建插入/更新/删除触发器,以使用以前的数据填充Trans_User表。请查看此questionthis代码项目文章。

答案 2 :(得分:0)

假设您正在使用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.
 }

}

您可能希望在概念失效后使用集合(List)和强类型对象组合所有这些。这将最大限度地减少对数据库的调用次数并简化代码。

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

 Trans_Id
 User_Name
 User_Gender
 User_Address
 Trans_Add_Date
相关问题