简体   繁体   中英

Need help stored procedure sql server 2008 output parameter c#

I have a little problem. My value is always null . I don't know why.

Code below:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UsunTowar]
     @id int output
AS SET NOCOUNT ON 
BEGIN
    if Exists (select top 1 Towar from Zamowienia where Towar = @id)
        begin
            set @id = 0
        end
    else
        begin
            delete from Towary where ID = @id
            set @id = 1
        end
END

Now c#:

con.Open();
SqlCommand cmd = con.CreateCommand();

cmd.CommandText = "EXECUTE UsunTowar @id";

cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
cmd.Parameters["@id"].Direction = ParameterDirection.Output;

cmd.ExecuteNonQuery();

string result = cmd.Parameters["@id"].Value.ToString();

con.Close();

Value string 'result' is always null . I tried many ways. Return value must be 0 or 1 .

Code sql is good. Please help me.

I use this:

    using(SqlConnection conn = new SqlConnection("myConnectionString"))
    {
        using(SqlCommand cmd = new SqlCommand("myStoredProcedure", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output;
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                // -1 if null
                int id = 0;
                if (!int.TryParse(cmd.Parameters["@id"].value, out id))
                    id = -1;
            }
            catch
            {
                throw;
            }

        }
    }

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