ALTER procedure [dbo].[sp_orders_by_employeeid2]
  @employeeid int,
  @ordercount int=0 output
as
  select orderid,customerid
  from orders
  where employeeid=@employeeid
  select @ordercount=count(*)
  from orders
  where employeeid=@employeeid
string source = @"server=z\zfy;" +
                             "integrated security=SSPI;" +
                             "database=Northwind";//ceshi为数据库名
            SqlConnection conn = new SqlConnection(source);
            conn.Open();            SqlCommand cmd = new SqlCommand("sp_orders_by_employeeid2", conn);
            cmd.CommandType = CommandType.StoredProcedure;            
            cmd.Parameters.Add(new SqlParameter("@employeeid",SqlDbType.Int,10,ParameterDirection.Input,false,0,0,"@employeeid",DataRowVersion.Default,2));
            cmd.Parameters.Add(new SqlParameter("@ordercount", SqlDbType.Int, 10, ParameterDirection.Output, true, 0, 0, "@ordercount", DataRowVersion.Default, null));            SqlDataReader read = cmd.ExecuteReader();
            while (read.Read())
            {
                Console.WriteLine(read[0] + "," + read[1]);
            }
            Console.WriteLine(cmd.Parameters["@ordercount"].Value);            conn.Close();取出cmd.Parameters["@ordercount"].Value为NULL,为什么呢?把SQL改成如下:ALTER procedure [dbo].[sp_orders_by_employeeid2]
  @employeeid int,
  @ordercount int=0 output
as
  select @ordercount=count(*)
  from orders
  where employeeid=@employeeid这样就没问题了,能这样取出cmd.Parameters["@ordercount"].Value参数,是因为执行了2次SELECT的原因吗?那如何才能即执行2次SELECT又能成功的取出@ordercount参数?

解决方案 »

  1.   

    加个 begin end试试  ALTER procedure [dbo].[sp_orders_by_employeeid2]
      @employeeid int,
      @ordercount int=0 output
    as
    begin
      select orderid,customerid
      from orders
      where employeeid=@employeeid
      select @ordercount=count(*)
      from orders
      where employeeid=@employeeid
    end
      

  2.   

    EXEC sp_executesql @StrSQL,N'@ordercount int out',@ordercount outhttp://topic.csdn.net/u/20091013/13/1ba85d9b-ef2e-41d1-9fd5-11218015264c.html
      

  3.   

    好了,自己找到问题在那了:
    while (sdread.Read())
       Console.WriteLine(sdread[0] + "," + sdread[1]);
    sdread.Close();//必须关闭,否则无法取出参数