如何从代码后台使用存储过程(带参数-具有int类型的返回值)?
我的存储过程如下所示:
ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
@Co_ID int
AS
-----------------
Declare @Sum bigint
-----------------
BEGIN
SELECT
@Sum = SUM(TotalPay)
FROM Noskheh
WHERE
(Co_ID = @Co_ID)
RETURN @Sum
END我想在后台代码中使用@Sum ...
你能告诉我怎么做吗?
提前感谢
诚挚的问候
发布于 2010-12-21 02:28:03
您需要设置SqlConnection和SqlCommand。如果您的代码最后包含RETURN @Sum语句,则需要这样做(定义一个RETURN_VALUE类型的参数):
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
_cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want
_cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.BigInt));
_cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;
_conn.Open();
_cmd.ExecuteNonQuery();
Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value);
_conn.Close();
}如果将返回语句替换为一个简单SELECT语句,将会容易得多:
SELECT @Sum在这种情况下,您可以使用我之前的简化版本-使用.ExecuteScalar()来检索从存储过程返回的单个行的单个值:
using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
_cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want
_conn.Open();
object result = _cmd.ExecuteScalar();
_conn.Close();
Int64 sum = Int64.Parse(result);
}这将调用您的存储过程,读取您返回的单个值,并将其转换为一个名为sum的int变量。
发布于 2010-12-21 02:26:28
发布于 2010-12-21 02:17:51
可以添加方向设置为ReturnValue的SqlParameter @Sum
示例:
SqlCommand cmd = new SqlCommand():
cmd.Connection = // place your SqlConnection object;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoreProcedureName";
cmd.Parameters.Add("@Sum", SqlDbType.BigInt).Direction = ParameterDirection.ReturnValuehttps://stackoverflow.com/questions/4492536
复制相似问题