使用 SqlCommand 从子 Table 更新父 table
Update Parent table from Child Table using SqlCommand
我有 2 个 table:
WorkSchedule
有 2 列 WorkScheduleID
和 WorkScheduleStatus
WorkShiftBid
有 3 列:WorkShiftBidID
、WSBidStatus
、WorkScheduleID
(WorkSchedule
table 的外键)
我想从 WorkShiftBid
table 更新 WorkSchedule
table。所以大致是这样的:
我在我的网站上按下一个按钮,它读取当前 WorkShiftBidID
并将 WSBidStatus
更新为 'Approved'。
但是,我想将 table 中的 WorkScheduleStatus
和 WSBidStatus
更新为 'Approved',其中 table 中的 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);
我应该如何更改它才能工作?
您不能使用一个更新命令更新 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;
我有 2 个 table:
WorkSchedule
有 2 列WorkScheduleID
和WorkScheduleStatus
WorkShiftBid
有 3 列:WorkShiftBidID
、WSBidStatus
、WorkScheduleID
(WorkSchedule
table 的外键)
我想从 WorkShiftBid
table 更新 WorkSchedule
table。所以大致是这样的:
我在我的网站上按下一个按钮,它读取当前 WorkShiftBidID
并将 WSBidStatus
更新为 'Approved'。
但是,我想将 table 中的 WorkScheduleStatus
和 WSBidStatus
更新为 'Approved',其中 table 中的 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);
我应该如何更改它才能工作?
您不能使用一个更新命令更新 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;