[英]How can I get the result of a stored procedure in C#?
Here is my code 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;
The stored procedure: 存储过程:
ALTER PROCEDURE [dbo].[Coupon_GetDiscountFromValidCouponCode]
@PKCouponCode varchar(50)
AS
SELECT *
FROM Coupon
WHERE CouponCode = @PKCouponCode AND Valid = 1
Here is how the DB looks like: 数据库的外观如下:
I encounter an error 我遇到错误
Input string was not in a correct format
输入的字符串格式不正确
I don't know what's thing is going wrong, any ideas? 我不知道出什么事了,有什么主意吗?
If you want the discount value, then you should return only the discount from the SP (since it is named GetDiscountfrom
...) 如果你想折现值,那么你应该从SP只返回折扣(因为它被命名为
GetDiscountfrom
...)
SELECT CouponDiscount FROM Coupon WHERE CouponCode = @PKCouponCode AND Valid = 1
This will make it a one-column resultset, which matches the access reader[0]
from C#. 这将使其成为一个单列结果集,该结果集与C#中的访问
reader[0]
相匹配。
The other option is of course to change the C# side to read the second item (index 1) or reference the column by name, eg 当然,另一个选择是更改C#端以读取第二项(索引1)或按名称引用该列,例如
r_discountValue = float.Parse(reader[1].ToString());
r_discountValue = float.Parse(reader["CouponDiscount"].ToString());
You would have got Input string was not in a correct format.
您可能
Input string was not in a correct format.
because it was reading "DIS_77" which float.parse
cannot process. 因为它正在读取
float.parse
无法处理的“ DIS_77”。
You are using first column ie CouponCode
for fetching discount. 您正在使用第一列,即
CouponCode
来获取折扣。 instead of that you need to use second column ie. 而不是你需要使用第二列即。
couponDiscount
So try something like this 所以尝试这样的事情
r_discountValue = float.Parse(reader["CouponDiscount"].ToString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.