【问题标题】:Update Parent table from Child Table using SqlCommand使用 SqlCommand 从子表更新父表
【发布时间】:2020-10-31 22:04:49
【问题描述】:

我有 2 张桌子:

  • WorkSchedule 有 2 列 WorkScheduleIDWorkScheduleStatus
  • WorkShiftBid 有 3 列:WorkShiftBidIDWSBidStatusWorkScheduleIDWorkSchedule 表的外键)

我想从WorkShiftBid 表更新WorkSchedule 表。所以大致是这样的:

我在我的网站上按下一个按钮,它会读取当前的 WorkShiftBidID 并将 WSBidStatus 更新为“已批准”。

但是,我想将两个表中的 WorkScheduleStatusWSBidStatus 更新为“已批准”,其中两个表中的 WorkScheduleID 相同。

我想出了这个查询,但它不起作用:

com.CommandText = "update WorkShiftBid b, WorkSchedule w" +
                  "set b.WSBidStatus ='Approved' and w.WorkScheduleStatus = 'Approved'" +
                  "where WorkShiftBidID = @id and w.WorkScheduleID = b.WorkScheduleID";
com.Parameters.AddWithValue("@id", id);

我应该如何改变它才能工作?

【问题讨论】:

  • 写一个存储过程?

标签: sql sql-server entity-framework sqlcommand


【解决方案1】:

您不能使用单个更新命令更新 2 个表。但是,您可以在一个批次中执行 2 次更新,或者如果您愿意,可以将它们作为 2 批次发送:

com.CommandText = @"update WorkShiftBid
  set WSBidStatus ='Approved'
  where WorkShiftBidID = @id;

update w
  set WorkScheduleStatus = 'Approved'
from WorkSchedule w
  inner join WorkShiftBid b
     on w.WorkScheduleID = b.WorkScheduleID
  where WorkShiftBidID = @id";

com.Parameters.Add("@id", SqlDbType.Int).Value = id;

【讨论】:

  • 如果您在第二个UPDATE 语句中使用from WorkSchedule w,那么您必须使用 UPDATE w(使用别名 ) 在 T-SQL 中
  • 我遇到了这个问题:“SqlException: Invalid object name 'WorkShiftBidID'。”当我运行时,它只更新了WorkShiftBid 表中的WSBidStatus。但是,它无法更新WorkSchedule 表。我认为查询的第二部分出了点问题。
  • @addsw,可能我写错了你的表名。编辑。
猜你喜欢
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
相关资源
最近更新 更多