简体   繁体   中英

How To Get Set Value From Stored procedure in C#

I have a stored procedure that client provided me

Like:

ALTER Proc [dbo].[XYZ]
    @Parameter varchar(100),
    @Parameter1 nvarchar(4000) out

   SET @APIString = "Test Test"

I have no rights to change this procedure.

When I execute procedure through C# I get a blank string from procedure

How to get the @Parameter1 value in my project?

C# Code:

SqlCommand cmd = new SqlCommand("dbo.XYZ", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parameter", Parameter);

cmd.Parameters.Add("@Parameter1", SqlDbType.VarChar,4000);
cmd.Parameters["@Parameter1"].Direction = ParameterDirection.Output;

conn.Open();

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    String = reader["@Parameter1"] != null ? reader["@Parameter1"].ToString() : "";
}

conn.Close();

@Parameter1 is an output parameter. You can get its value the same way you set the values for input parameters, eg

var cmd = new SqlCommand("dbo.XYZ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parameter", inputValue);

// add the output parameter
cmd.Parameters.Add("@Parameter1", SqlDbType.NVarChar).Direction =
    ParameterDirection.Output;

cmd.ExecuteNonQuery();

string parameter1 = (string)cmd.Parameters["@Parameter1"].Value;

You should also use ExecuteNonQuery unless the store procedure returns values with a select statement.

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