如何在mysql中获取自动递增的存储过程

时间:2019-01-24 00:37:08

标签: c# mysql sql

我正在运行以下代码来调用p_CreateRequest。我只想找回ID,但我得到一个字段“ ID”,没有默认值错误。帮助

 using (var conn = Conn)
            {
                using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("p_CreateRequest", conn))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("CREATED_DATE", cREATED_DATE));
                    cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("WORKFLOW_ID", wORKFLOW_ID));
                    cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("CREATED_BY_USER_ID", cREATED_BY_USER_ID));
                    cmd.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ID", iD));
                    cmd.Parameters["ID"].Direction = System.Data.ParameterDirection.Output;
                    cmd.ExecuteNonQuery();

                    iD = (int)cmd.Parameters["ID"].Value;
                    return iD;
                }
            }

存储过程代码为

CREATE DEFINER="finnsch"@"%" PROCEDURE "p_CreateRequest"(CREATED_DATE datetime,
WORKFLOW_ID int, CREATED_BY_USER_ID varchar(50),INOUT ID int)
BEGIN
  DECLARE LASTCHANGEDATE Date;
  SET LASTCHANGEDATE = Now();
  INSERT INTO REQUEST 
  (CREATED_DATE,WORKFLOW_ID,CREATED_BY_USER_ID,
CURRENT_STEP_ID,LAST_ACTION_BY,LAST_EDIT_DATE)
 select 
 CREATED_DATE,WORKFLOW_ID,CREATED_BY_USER_ID,s.ID,
CREATED_BY_USER_ID,LASTCHANGEDATE
 from 
 STEP s where s.WORKFLOW_ID=WORKFLOW_ID and s.IS_INITIAL=1;
 set ID = Last_Insert_ID();
END

1 个答案:

答案 0 :(得分:0)

需要更改表并将ID设置为:

id int(20) NOT NULL AUTO_INCREMENT,

还要检查MySql是否在Strict SQL Mode中。如果是,则需要运行查询:

SET GLOBAL sql_mode=''.

您还可以修改my.cnf / my.ini,以确保未设置STRICT_ALL_TABLES和/或STRICT_TRANS_TABLES。请参阅此以获取更多信息:

Field 'id' doesn't have a default value?