这是我在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
以下是数据库的外观:
我遇到错误
输入字符串的格式不正确
我不知道出了什么问题,有什么想法吗?
答案 0 :(得分:3)
如果您想要折扣价值,那么您应该只返回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”。
答案 1 :(得分:2)
您正在使用第一列,即。CouponCode
来获取折扣。而不是你需要使用第二列即。 couponDiscount
所以尝试这样的事情
r_discountValue = float.Parse(reader["CouponDiscount"].ToString());