简体   繁体   English

如何在asp.net中使用存储过程的返回值?

[英]How to use the return value of stored procedure in asp.net?

I use this stored procedure for get the number of records 我使用此存储过程获取记录数

ALTER PROCEDURE  [dbo].[Asbabbazi_A]
@count int output
AS
BEGIN
if(@count=0)
set @count =( select count(*)   from dbo.Table_asbabbazi where (active= 0))
end

now I want use the @count in my project.I wrote this codes for use the @count in method. 现在我想在项目中使用@count。我编写了使用@count方法的代码。

 SqlConnection con = new SqlConnection(constr);
        cmd.Connection = con;
        con.Open();
        DataAdapter.SelectCommand = cmd;
        DataSet ds = new DataSet("haftehbazardb");
        SqlCommandBuilder bldr = new SqlCommandBuilder(DataAdapter);

        SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
        returnParameter.Direction = ParameterDirection.ReturnValue;

        cmd.ExecuteNonQuery();

        DataAdapter.Fill(ds, Table_asbabbazi);
        countrecords = (int)returnParameter.Value;

this codes have no error but when i use the (countrecords ) in my project the value of (countrecords ) is zero that is not right . 此代码没有错误,但是当我在项目中使用(countrecords)时(countrecords)的值为零,这是不对的。 Please help 请帮忙

If you want to get the value as the output of the stored procedure, you will need to return it. 如果要获取该值作为存储过程的输出,则需要将其返回。

ALTER PROCEDURE  [dbo].[Asbabbazi_A]
@count int output
AS
BEGIN
if(@count=0)
set @count =( select count(*)   from dbo.Table_asbabbazi where (active= 0))

return @count
end

You are confusing output parameters with a return value. 您正在将输出参数与返回值混淆。

Return value is generally used to indicate the status of your procedure, it will be 0 if not specified, eg 返回值通常用于指示过程的状态,如果未指定,则返回0。

CREATE PROCEDURE dbo.TestProc @Out INT OUTPUT
AS
BEGIN
    BEGIN TRY
        SET @Out = 1 / 0;
        RETURN 0;
    END TRY
    BEGIN CATCH
        SET @Out = 0;
        RETURN 1;
    END CATCH
END

Then calling this with T-SQL; 然后用T-SQL调用它;

DECLARE @out INT, @return INT;  
EXECUTE @Return = dbo.TestProc @out OUT;
SELECT [Return] = @return, [out] = @out;

Will give: 会给:

Return | out
-------+-----
   1   |  0

Since 0 is the default return value, this is why you are getting 0 out from returnParameter , you need to use ParameterDirection.Output : 由于0是默认返回值,因此这就是为什么要从returnParameter中获取0的returnParameter ,您需要使用ParameterDirection.Output

SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;

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

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