【问题标题】:How can I get the result of a stored procedure in C#?如何在 C# 中获取存储过程的结果?
【发布时间】:2026-01-24 06:45:01
【问题描述】:

这是我的 C# 代码:

float r_discountValue = 0;

SqlConnection con = Constant.GetConnection();

SqlCommand cmd = new SqlCommand("Coupon_GetDiscountFromValidCouponCode", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@PKCouponCode", SqlDbType.VarChar);
cmd.Parameters["@PKCouponCode"].Value = "DIS_77";

try
{
    con.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    if(reader.Read()){
       r_discountValue = float.Parse(reader[0].ToString());
    }

    reader.Close();
}
catch(Exception exception)
{
    throw exception;
}
finally{
    con.Close();
}

return r_discountValue;

存储过程:

ALTER PROCEDURE [dbo].[Coupon_GetDiscountFromValidCouponCode]
    @PKCouponCode varchar(50)
AS
    SELECT * 
    FROM Coupon 
    WHERE CouponCode = @PKCouponCode AND Valid = 1

这是数据库的样子:

我遇到了一个错误

输入的字符串格式不正确

我不知道出了什么问题,有什么想法吗?

【问题讨论】:

  • 您能否详细说明您的实际问题?你面临什么问题?
  • 您的代码发生了什么?会报错吗?
  • 抱歉,我更新了我的问题。 Input string was not in a correct format. 发生错误。

标签: c# sql database sql-server-2008 stored-procedures


【解决方案1】:

如果您想要折扣值,那么您应该只返回来自 SP 的折扣(因为它名为 GetDiscountfrom...)

SELECT CouponDiscount FROM Coupon WHERE CouponCode = @PKCouponCode AND Valid = 1

这将使其成为单列结果集,与 C# 中的访问 reader[0] 匹配。

另一种选择当然是更改C#端以读取第二项(索引1)或按名称引用列,例如

r_discountValue = float.Parse(reader[1].ToString());
r_discountValue = float.Parse(reader["CouponDiscount"].ToString());

你会得到Input string was not in a correct format.,因为它正在读取float.parse无法处理的“DIS_77”。

【讨论】:

    【解决方案2】:

    您正在使用第一列即CouponCode 获取折扣。而不是你需要使用第二列,即。 couponDiscount

    所以试试这样的

     r_discountValue = float.Parse(reader["CouponDiscount"].ToString());
    

    【讨论】:

      最近更新 更多