c# - 获取第一个表插入的值到第二个表

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

我有两个事务范围的查询。我需要将第一个表插入值插入到我的详细表中。在这里,第一个表中的 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
}

最佳答案

请检查下面我的回答

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

关于c# - 获取第一个表插入的值到第二个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259777/

相关文章:

c# - Log4net XMLLayout 产生太多元素

c# - 编写大文件的最佳实践

mysql - 不确定我是否正确地执行了 sql 查询

php - 从一个表查询后从另一表获取更多信息并连接结果

c# - 我可以使用 Telegram 机器人删除用户消息吗?

c# - 集成 C# 和 R 问题

mysql - 使用 GROUP BY 时如何获取所有行?

sql - 具有基于 GROUPING SETS 的数据集的展开-折叠报告

sql - 查明总和值何时达到 SQL 中的某个检查点

sql-server - ';'在 SQL 语句的开头