【问题标题】:Get First Tables Inserted Values to Second table获取第一个表插入值到第二个表
【发布时间】:2019-01-18 18:43:17
【问题描述】:

我有两个关于事务范围的查询。我需要将第一个表插入值插入到我的详细信息表中。在这里,我在第一个表中的 NewsId 是主键和自动递增的主键。我需要将该 id 插入第二个表(Detail 表)

// Some code here

transaction = con.BeginTransaction();

// NewsId is the primary key and auto-incremented. I need to retrieve 
// that value and insert it into the second table 
string query1 = "INSERT INTO ABC(NewsCode, Comment) VALUES (@NewsCode, @Comment)"; 
cmd = db.GetSqlStringCommand(query1);
cmd.Transaction = transaction;

db.AddInParameter(cmd, "NewsCode", DbType.Int32, News.NewsCode);
db.AddInParameter(cmd, "Comment", DbType.String,News.Comment);

db.ExecuteNonQuery(cmd, transaction);

foreach (var item in NewsTotal.items)
{
    // I'm going to insert into the `Detail` table and I need the 
    // previously inserted table's NewsId
    string newsItemsQuery = @"INSERT INTO [dbo].[TBL_T_NewsItems] ([NewsId], [ItemId])
                              VALUES (@NewsId, @Comment)";

    // some code here
}

【问题讨论】:

    标签: c# sql sql-server asp.net-mvc


    【解决方案1】:

    请在下方查看我的回答

    transaction = con.BeginTransaction();
    string query1 ="Insert Into ABC(NewsCode,Comment) output INSERTED.ID Values (@NewsCode,@Comment)"; 
    cmd = db.GetSqlStringCommand(query1);
    cmd.Transaction = transaction;
    cmd.Connection = con;
    
    db.AddInParameter(cmd, "NewsCode", DbType.Int32, News.NewsCode);
    db.AddInParameter(cmd, "Comment", DbType.String,News.Comment);
    
    int modifiedRowId =(int)cmd.ExecuteScalar();
    

    【讨论】:

      【解决方案2】:

      好的,这就是你可以做的

      foreach (var item in NewsTotal.items) { 
      string newsItemsQuery = @"INSERT INTO [dbo].[TBL_T_NewsItems] ([NewsId],[ItemId]) SELECT NewsId, ItemId FROM ABC"; 
       }
      

      【讨论】:

      • 这不知道吗?因为我在交易范围内
      • 好的,看看@simonare 的答案。另一个可用的选项是在 ABC 表上为 INSERT 创建一个触发器,并将新生成的 id 存储在另一个表中......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多