.NET 获得sql存储过程并返回值
public string RunProcedure(OleDbParameter[] paramInput, OleDbParameter[] paramOutput, string procName)
{
int cnt = 0;
string returnString = "-2";
try
{
String ConnStr = OleDbHelper.GetOleDBConnection();
using (OleDbConnection connection = new OleDbConnection(ConnStr))
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = procName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
for (int i = 0; i < paramInput.Length; i++)
{
cmd.Parameters.Add(paramInput[i]);
}
for (int i = 0; i < paramOutput.Length; i++)
{
cmd.Parameters.Add(paramOutput[i]);
}
cnt = cmd.ExecuteNonQuery();
System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
returnString = "错误标识";
}
finally
{
if (cnt > 0)
{
for (int i = 0; i < paramOutput.Length; i++)
{
returnString = paramOutput[i].Value.ToString();
}
}
this.Close();
}
return returnString;
}
做下解释:
1. cnt=cmd.ExecuteNonQuery() 这里cnt是改动的记录数 如果没有修改返回-1
2. 如果是output定义的出参的话 在执行完上述语句后用returnString = paramOutput[i].Value.ToString();接收参数。
3. 返回结果集,经过测试。
System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
4. 接受存储过程中return返回的值:
cmd.Parameters.Add("@return", SqlDbType.Int);
cmd.Parameters["@return"].Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
string returnS=cmd.Parameters["@return"].Value.ToString();