ExecuteScalar不会返回当前行的第一列

时间:2017-11-03 20:25:28

标签: c# asp.net ado.net

我的表格中有一个自动递增的主键列ProductId。这是我的代码,我使用存储过程插入产品 - 我希望我的插入行第一列值只是productIdExecuteScalar总是返回0 - 为什么?

Command = new SqlCommand("spInsertProduct", Connection);
Command.CommandType = CommandType.StoredProcedure;

Command.Parameters.AddRange(aSqlParameter);

Connection.Open();
Int32 productId = Convert.ToInt32(Command.ExecuteScalar());

1 个答案:

答案 0 :(得分:1)

存储过程:

// Using Output parameter
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);

SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AddEmployeeReturnIDwithoutput";

cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text.Trim();
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text.Trim();
cmd.Parameters.Add("@BirthDate", SqlDbType.DateTime).Value = txtBirthDate.Text.Trim();
cmd.Parameters.Add("@City", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = txtCountry.Text.Trim();
cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output;    

cmd.Connection = con;

try
{
    con.Open();
    cmd.ExecuteNonQuery() ;
    string id = cmd.Parameters["@id"].Value.ToString() ;
    lblMessage.Text = "Record inserted successfully. ID = " +  id;
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    con.Close();
    con.Dispose();
}

检索数据的逻辑:

{{1}}

这就是你应该怎么做..如果你没有从存储过程中返回任何东西,你就不会得到任何价值