簡體   English   中英

如何使用 SQL 查詢更新子表

[英]How do to Update Child Table using SQL Query

我想通過單擊一個按鈕來幫助更新 2 個表。 我將更新一個名為 WorkSchedule 的表和另一個名為 WorkShiftBid 的表。 我想要實現的是,更新 WorkSchedule 表並將名為“WorkScheduleStatus”的列設置為“Pending”(我已經完成了),同時使用另一個 SQL 查詢來更新另一個名為 WorkShiftBid 的表。

WorkShiftBid 表供參考

通過參考,我能夠生成新的 WorkShiftBidID、捕獲 WSBidDateTime(系統時間)和 WSBidStatus。 我一直在嘗試從 WorkSchedule 表中獲取 WorkScheduleID,如何使用 SQLQuery 進行表連接並獲取 WorkScheduleID?

 public async Task<IActionResult> DisplaySchedule(Guid? id)
    {
        SqlConnection con = new SqlConnection();
        SqlCommand com = new SqlCommand();
        SqlDataReader dr;


        
       connectionString();
        con.Open();
        com.Connection = con;
        com.CommandText = @"update WorkSchedule set WorkScheduleStatus ='Test' where WorkScheduleID = @id;
        
        insert into WorkShiftBid (WorkShiftBidID,WSBidDateTime,WSBidStatus) values (NewID(),GetDate(),'Pending')";


        com.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = id;
        dr = com.ExecuteReader();

        
     

        if (dr.Read())
        {
            con.Close();
            return RedirectToAction(nameof(DisplaySchedule));
        }
        else
        {
            con.Close();
            return RedirectToAction(nameof(DisplaySchedule));
        }

        

        void connectionString()
        {
            con.ConnectionString = "";

        }
    }
   

您需要添加第二個 output 參數,如下所示:

com.CommandText = @"update WorkSchedule set WorkScheduleStatus ='Test' where WorkScheduleID = @id;
        
insert into WorkShiftBid (WorkShiftBidID,WSBidDateTime,WSBidStatus) values (NewID(),GetDate(),'Pending');
set @newId = scope_identity();";

com.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = id;
var p = com.Parameters.Add("@newId", SqlDbType.Int32);
p.Direction = ParameterDirection.Output
dr = com.ExecuteReader();


var newId = (int)dr.Parameters["@newId"].value;

這段代碼只是從我的腦海中浮現出來的,所以它可能需要一些編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM