Get First Tables Inserted Values to Second table

时间:2019-01-18 18:43:18

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

I have two queries with transaction scope. I need to insert first tables inserted value to my detail table. In here my NewsId in first table is the primary key and an auto-incremented one. I need to insert that id into the second table (Detail table)

// 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
}

2 个答案:

答案 0 :(得分:1)

Please check my answer below

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();

答案 1 :(得分:0)

OK this is what u can do

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