2013-04-24 80 views
0

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

下面是DB的样子:

enter image description here

我遇到一个错误

输入字符串的不正确的格式

我不知道发生了什么事情是怎么了,什么想法?

+1

你能详细说明你的实际问题吗?你面临什么问题? – Sachin 2013-04-24 02:20:40

+0

你的代码发生了什么?它会给出错误吗? – RichardTheKiwi 2013-04-24 02:20:46

+0

SorrY,我更新了我的问题。 '输入字符串格式不正确.'发生错误。 – DNB5brims 2013-04-24 02:22:59

回答

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.,因为它是阅读“DIS_77”这float.parse无法处理。

2

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

所以尝试这样的事情

r_discountValue = float.Parse(reader["CouponDiscount"].ToString()); 
相关问题