我正在做一个大学出勤项目(Winforms,Mysql,C#)
我想在所有期间列中更新0到P,1到Ab和2到OD。为此我写了一个for循环和三个更新查询。
在一个查询中执行此操作是否有任何可能的想法?
请帮帮我......
for (int i = 1; i <= 8; i++)
{
string period = "Period" + i;
string t1p = period1;
command.CommandText = "update attendance_daily_rpt set " + t1p + " = 'P' where " + t1p + " = 0";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
command.CommandText = "update attendance_daily_rpt set " + t1p + " = 'Ab' where " + t1p + " = 1";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
command.CommandText = "update attendance_daily_rpt set " + t1p + " = 'OD' where " + t1p + " = 2";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
提前致谢...
答案 0 :(得分:3)
创建一个用于维护映射的表(attendance_daily_rpt_map):
+-----------+---------+ | FromValue | ToValue | +-----------+---------+ | 0 | P | | 1 | Ab | | 2 | OD | +-----------+---------+
然后更改您的查询:
UPDATE
attendance_daily_rpt
INNER JOIN attendance_daily_rpt_map ON attendance_daily_rpt.t1p = attendance_daily_rpt_map.FromValue
SET
attendance_daily_rpt.t1p = attendance_daily_rpt_map.ToValue
答案 1 :(得分:2)
SQL:
SET t1p =
CASE t1p
WHEN '1' THEN 'AB'
WHEN '2' THEN 'OD'
END
自己制作C#字符串;)
答案 2 :(得分:2)
可能但它很可能是一个怪物,可能比二十四个单独的目标更新表现更差。除了以下事实之外,我没有看到您当前的解决方案有什么特别的错误:
我试着从类似的东西开始:
connection.Open();
// Start transaction with whatever it takes.
for (int i = 1; i <= 8; i++) {
string t1p = "Period" + i;;
command.CommandText = "update attendance_daily_rpt set " + t1p
+ " = 'P' where " + t1p + " = '0'";
command.ExecuteNonQuery();
command.CommandText = "update attendance_daily_rpt set " + t1p
+ " = 'Ab' where " + t1p + " = '1'";
command.ExecuteNonQuery();
command.CommandText = "update attendance_daily_rpt set " + t1p
+ " = 'OD' where " + t1p + " = '2'";
command.ExecuteNonQuery();
}
// Commit transaction.
connection.Close();
你也可以简单地将单个语句下载到数组查找中,例如:
string[] vals = new string[] {"P", "Ab", "OD"};
connection.Open();
// Start transaction with whatever it takes.
for (int i = 1; i <= 8; i++) {
string t1p = "Period" + i;;
for (int j = 0; j < vals.Length; j++) {
command.CommandText = "update attendance_daily_rpt set " + t1p
+ " = '" + vals[j] +"' where " + t1p + " = '" + j + "'";
command.ExecuteNonQuery();
}
}
// Commit transaction.
connection.Close();
答案 3 :(得分:1)
您可以使用CASE声明
UPDATE
attendance_daily_rpt
SET
PeriodX = CASE PeriodX
WHEN '0' THEN 'P'
WHEN '1' THEN 'Ab'
WHEN '2' THEN 'OD'
ELSE PeriodX
END