当我使用 sql 存储过程运行以下代码时,我得到 -1 而不是正确的结果。代码有什么问题?请帮忙。
ALTER PROCEDURE GetTopMaterial
AS
BEGIN
SELECT TOP (1) MaterialId
FROM Materials
END
public static int GetTopMaterial()
{
SqlHelper objSqlHelper = new SqlHelper();
return (int)objSqlHelper.ExecuteScalar("GetTopMaterial");
}
int id =Cart.GetTopMaterial()
public object ExecuteScalar (string query)
{
SqlConnection cnn = new SqlConnection (strConnectionString);
SqlCommand cmd = new SqlCommand (query, cnn);
if (query.StartsWith ("SELECT") | query.StartsWith ("select"))
{
cmd.CommandType = CommandType.Text;
}
else
{
cmd.CommandType = CommandType.StoredProcedure;
}
cnn.Open ();
object retval = cmd.ExecuteNonQuery ();
cnn.Close ();
return retval;
}
public object ExecuteScalar(string query, params SqlParameter[] parameters)
{
SqlConnection cnn = new SqlConnection(strConnectionString);
SqlCommand cmd = new SqlCommand(query, cnn);
if (query.StartsWith("SELECT") | query.StartsWith("select"))
{
cmd.CommandType = CommandType.Text;
}
else
{
cmd.CommandType = CommandType.StoredProcedure;
}
for (int i = 0; i <= parameters.Length - 1; i++)
{
cmd.Parameters.Add(parameters[i]);
}
cnn.Open();
object retval = cmd.ExecuteScalar();
cnn.Close();
return retval;
}