简体   繁体   中英

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.

 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 . 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

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;

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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