为什么输出参数在c#级别返回0?

时间:2015-10-06 19:58:20

标签: c# sql asp.net sql-server

我试图从商店程序中获取输出,但在C#中它给了我0.

 public short SelectOccupantTypesByOccupantTypeID(Int64 OccupantID)
            {

                SqlCommand SqlCom = new SqlCommand("SelectOccupantTypesByOccupantTypeID", DatabaseConnection.OpenConnection());
                SqlCom.CommandType = CommandType.StoredProcedure;
                SqlCom.Parameters.AddWithValue("@pk_Occupants_OccupantID", OccupantID);
                SqlParameter sqlParamOccupantTypeID = new SqlParameter("@OccupantTypeID", SqlDbType.SmallInt);
                sqlParamOccupantTypeID.Direction = ParameterDirection.Output;
                SqlCom.Parameters.Add(sqlParamOccupantTypeID);
                short OccupantTypeID = Convert.ToInt16(sqlParamOccupantTypeID.Value);
                SqlCom.ExecuteNonQuery();
                DatabaseConnection.CloseConnection();

                return OccupantTypeID;

            }

试图得到它

protected void ddlOccupants_SelectedIndexChanged(object sender, EventArgs e)
    {
        Int64 OccupantID= Convert.ToInt64(ddlOccupants.SelectedValue);
        Int16 OccupantTypeID= MngOccupants.SelectOccupantTypesByOccupantTypeID(OccupantID);
        txtBoxMonthlyInstallment.Text = OccupantTypeID.ToString();

    }

SP:

alter PROCEDURE [dbo].[SelectOccupantTypesByOccupantTypeID] 

    @pk_Occupants_OccupantID bigint,
    @OccupantTypeID smallint output

AS
BEGIN

         Set @OccupantTypeID= (Select Occupants.OccupantsOccupantTypeID 
         From Occupants
         Where Occupants.pk_Occupants_OccupantID= @pk_Occupants_OccupantID)

         return @OccupantTypeID

END

但是sp在sql级别返回正确的值但在C#级别返回0。为什么?

1 个答案:

答案 0 :(得分:2)

在执行查询之前,您正在读取参数的值,交换顺序。

SqlCom.ExecuteNonQuery();
short OccupantTypeID = Convert.ToInt16(sqlParamOccupantTypeID.Value);

但是,您提交其他“不良做法”,您的连接应该包含在using语句中,而不是在整个程序中重复使用。 ADO.NET已经实现了Connection Pooling,你不需要自己动手,只需要根据需要建立短暂的连接,当你处理它们时,它们将被返回到池中。