首先定义存储过程如下:(sqlserver 2008)

use studb2008
go
create procedure proc_test
@num int=-1 output
as
  set @num=10 --输出参数
  return 2  --返回值
  go

 

然后在vs中写如下c#代码:

namespace StoreProcedureTest
{
    class Program
    {
        static void Main(string[] args)
        {

            string s = @"Data Source=.\sql2008express;Initial Catalog=studb2008;User ID=sa;Password=sa";
            SqlConnection con = new SqlConnection(s);
            SqlCommand command = new SqlCommand();
            command.Connection = con;
            command.CommandText = "proc_test"; //proc_test为存储过程的名字
           command.CommandType = CommandType.StoredProcedure; //设置执行的类型
            SqlParameter para = new SqlParameter("@a",SqlDbType.Int);//任意定义一个变量,来接收返回值参数
            para.Direction = ParameterDirection.ReturnValue;   //注意这里1 表示接收返回值
            command.Parameters.Add(para);
            SqlParameter para2 = new SqlParameter("@num", SqlDbType.Int); //第二个变量来接收存储过程的输出参数
            para2.Direction = ParameterDirection.Output;   //注意这里2 表示接收输出值
          command.Parameters.Add(para2);
            con.Open();
            command.ExecuteNonQuery();
            int n = (int)command.Parameters["@a"].Value;
            int n2 = (int)command.Parameters["@num"].Value;
            Console.WriteLine(“n:”+n+":n2="+n2); //分别输出返回值和输出参数的值。分别是2和10
            Console.ReadLine();
            con.Close();

        }
    }
}