1

我想手动创建一个 ID 字段,我在其中执行 MAX + 1,并且我想在一个 QUERY 中执行它,所以我确定 2 个条目无法获得相同的字段。

        using (MySqlConnection dbConn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ProjektConStr"].ConnectionString))
    {
        dbConn.Open();
        using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Submission (CaseId , SubjectId, CenterId, EmployeeName, Reason, Description, Explanation, Date, Done, ChiefLevel) VALUES (MAX(CaseId)+1, @subject_id, @center_id, @employee_name, @reason, @description, @explanation, @date, @done, @chief)", dbConn))
        {
            cmd.Parameters.AddWithValue("date", submission.Date);
            cmd.Parameters.AddWithValue("subject_id", submission.SubjectId);
            cmd.Parameters.AddWithValue("center_id", submission.CenterId);
            cmd.Parameters.AddWithValue("employee_name", submission.EmployeeName);
            cmd.Parameters.AddWithValue("reason", submission.Reason);
            cmd.Parameters.AddWithValue("description", submission.Description);
            cmd.Parameters.AddWithValue("explanation", submission.Explanation);
            cmd.Parameters.AddWithValue("done", false);
            cmd.Parameters.AddWithValue("chief", false);
            cmd.ExecuteNonQuery();
        } 
    }
4

3 回答 3

3
          Use subquery to select max and insert a value 

插入提交(CaseId、SubjectId、CenterId、EmployeeName、原因、描述、解释、日期、完成、ChiefLevel)值(

          (1 + coalesce((SELECT max(CaseId) FROM Submission), 0))

、@subject_id、@center_id、@employee_name、@reason、@description、@explanation、@date、@done、@chief)

于 2012-06-21T12:44:13.810 回答
0
 using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Submission 
 (CaseId , SubjectId, CenterId, EmployeeName, Reason, Description, Explanation, 
 Date, Done, ChiefLevel) 
 VALUES ((select MAX(CaseId)+1 from YourTable), 
 @subject_id, @center_id, @employee_name, @reason, @description, @explanation,
 @date, @done, @chief)", dbConn))
于 2012-06-21T12:44:37.153 回答
0

您不能在单个查询中执行此操作,您必须获取 MAX_id 然后递增它,然后插入,或者您可以将表设为自动递增,在这里您不必在插入查询中包含 id。

于 2012-06-21T12:45:21.640 回答