I am trying to get a string return value from a stored procedure, but I am getting null. Stored procedure runs fine and return the expected string (I checked result using SQL Server Profiler) but I get empty string in my code.
public static string GetStringValue(string pCode)
{
String strConnString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
string returnValue = "";
cmd.CommandText = "usp_GetStringValue";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = new SqlConnection(strConnString);
cmd.Parameters.AddWithValue("@pcode", pCode);
//cmd.Parameters.AddWithValue("@Result", "");
SqlParameter sqlParam = new SqlParameter("@Result", "");
cmd.Parameters.Add(sqlParam);
sqlParam.Direction = ParameterDirection.Output;
cmd.Connection.Open();
cmd.ExecuteScalar();
//cmd.ExecuteNonQuery();
returnValue = Convert.ToString(cmd.Parameters["@Result"].Value);
cmd.Connection.Close();
return returnValue;
}
Here is my Stored Procedure
ALTER PROCEDURE [dbo].[usp_GetStringValue]
@pcode Varchar (4),
@Result varchar(5000) OUTPUT
AS
BEGIN
SET @Result=(Select pPath from mytable where pcode = @pcode)
print @Result
END
Try adding the @Result before adding any other parameters because it's an Output parameter. Rearrange the code as listed below. It's worked for me in the past. I will probably get flamed for this, but it's Friday.
SqlParameter sqlParam = new SqlParameter("@Result", "");
cmd.Parameters.Add(sqlParam);
sqlParam.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.AddWithValue("@pcode", pCode);
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.