-2

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

这是我尝试过的:

 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的值是“安全的”,但在getsparameters[0].Value = (string) status;行。如何解决这个问题?parameters[0].valuenull

4

2 回答 2

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
于 2012-10-01T20:29:55.347 回答
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
于 2012-10-01T20:18:41.190 回答