【发布时间】:2021-12-03 00:51:20
【问题描述】:
我有表 SelectedType 的列 type_1 ... type_2_3 的数据类型为 bit:
P_ID type_1 type_1_1 type_1_2 type_1_3 type_2 type_2_1 type_2_2 type_2_3
1 0 1 1 0 0 1 0 1
2 1 0 1 0 0 1 0 0
3 1 0 1 0 0 1 0 0
4 0 0 0 1 1 1 1 1
...and so on
和 JSON 数组
[
{"value": "type_1_1"}, {"value": "type_2_1"}, {"value": "type_2_3"}
]
如何使用 for 循环更新 SQL Server 表,如果 {"value": "type_1_1"} 等于表列名 type_1_1 则将值设置为 1,或者如果值为 1 则设置为 0?
这是我目前正在尝试的:
public bool UpdatePredictSubGoalType(int id, string _selectedTypes)
{
string a = "[]";
string item = _selectedTypes;
if (!item.Contains('[') && !item.Contains(']'))
{
string c = a.Insert(1, _selectedTypes);
item = c;
}
bool res = false;
JArray Ja = JArray.Parse(item);
string sqlstr = "";
try
{
using (conn = new SqlConnection(CommonDA.GetConnectionString()))
{
conn.Open();
trans = conn.BeginTransaction();
try
{
for (int i = 0; i <= Ja.Count - 1; i++)
{
string x = Ja[i]["value"].ToString();
SqlCommand cmd = conn.CreateCommand();
sqlstr = @"Update SelectedType set "+ x +" = (0 or 1, i don't know how to do) where id = @id AND " + x + " = @" + x;
cmd.CommandText = sqlstr;
cmd.Transaction = trans;
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
trans.Commit();
conn.Close();
res = true;
}
}
catch (Exception Err)
{
trans.Rollback();
CommonLB.SystemError(Err.Message);
CommonLB.SystemError("Data", "SQL:" + sqlstr);
}
}
}
catch (Exception Err)
{
throw new ApplicationException(Err.Message, Err);
}
return res;
}
【问题讨论】:
-
如果我正确理解您的要求,请将值设置为
1 - currentvalue? -
您从哪里获得价值? json 只有列名,但没有这些列的值
-
@Nonik 我假设“存在列 = 1,不存在列 = 0”
-
我还假设 json 包含一个我们看不到的 ID
-
我明白了,所以列将始终是静态的,在这种情况下,创建一个包含所有列的数组,根据缺失的列确定缺少哪些列,设置您的值
标签: c# sql-server asp.net-core