为什么SqlParameter没有获得价值?

时间:2012-10-01 20:03:23

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

我正在尝试使用字符串初始化SqlParameter的值。但为什么它没有得到价值?

这就是我的尝试:

 int loadChart(string status)
 {
        connect();

        SqlParameter[] parameters ={
                                      new SqlParameter("status", SqlDbType.VarChar, 10),
                                      new SqlParameter("count", SqlDbType.Int, 4)
                                  };

        parameters[0].Value = status;
        parameters[1].Direction = ParameterDirection.Output;

        SqlCommand cmd = new SqlCommand("sp_Arsenic_getSourceStatusCount", objConnection);

        foreach (SqlParameter param in parameters)
        {
            cmd.Parameters.Add(param);
        }

        cmd.ExecuteNonQuery();

        disConnect();

        int count;
        count =(int) parameters[1].Value;

        return count;
    }
}

存储过程:

alter procedure sp_Arsenic_getSourceStatusCount
@status varchar(10),
@count int
as
select @count=COUNT(status) from Arsenic_WaterSource where status=@status
return 1

插入断点我发现字符串变量status的值为“安全”,但在parameters[0].Value = (string) status;parameters[0].value获取null。如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

您没有在程序中将@count参数定义为OUTPUT参数:

alter procedure sp_Arsenic_getSourceStatusCount
@status varchar(10),
@count int OUTPUT  /* <--------------  */
as
select @count=COUNT(status) from Arsenic_WaterSource where status=@status
return 1

答案 1 :(得分:1)

试试这个:

connect();

SqlCommand cmd = new SqlCommand("sp_Arsenic_getSourceStatusCount", objConnection);

cmd.Parameters.Add(new SqlParameter("@status", status));
SqlParameter pCount = new SqlParameter("@count", 0);
pCount.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(pCount);

cmd.ExecuteNonQuery();

disConnect();

int count = Convert.ToInt32(parameters[1].Value);

return count;

而且:

alter procedure sp_Arsenic_getSourceStatusCount
@status varchar(10),
@count int = 0 OUTPUT
as
set nocount on
select @count=COUNT(status) from Arsenic_WaterSource where status=@status
go