繁体   English   中英

如何获得C#中存储过程的结果?

[英]How can I get the result of a stored procedure in C#?

这是我在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

数据库的外观如下:

在此处输入图片说明

我遇到错误

输入的字符串格式不正确

我不知道出什么事了,有什么主意吗?

如果你想折现值,那么你应该从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”。

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

所以尝试这样的事情

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM