11

I have stored procedure, which works great in MS SQL management studio.

When I try to use it in VS rows returns fine, but value of output parameters is NULL.

SqlCommand cmd = new SqlCommand("proc_name", conn);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@p_SomeVal", SqlDbType.Int));
cmd.Parameters["@p_SomeVal"].Direction = ParameterDirection.Output;

rdr = cmd.ExecuteReader();
//...process rows...

if (cmd.Parameters["@p_SomeVal"].Value != null)
SomeVal = (int)cmd.Parameters["@p_SomeVal"].Value;

cmd.ExecuteNonQuery(); Has the same result.

USE [db_name]
GO

DECLARE @return_value int,
    @p_SomeValue int

EXEC    @return_value = [dbo].[Proc_name]
    @p_InputVal = N'aa',
    @p_SomeValue = @p_SomeValue OUTPUT

SELECT  @p_SomeValue as N'p_SomeValue'

SELECT  'Return Value' = @return_value

GO
11
  • What's the procedure look like? Are you running it in the same database in VS and in SSMS? Commented Sep 15, 2013 at 8:23
  • @Oded yes DB is the same. And parameters is the same. Commented Sep 15, 2013 at 8:24
  • 4
    By the way you should be testing against DBNull.Value, not null. Commented Sep 15, 2013 at 8:25
  • @Oded Tried that too with the same luck Commented Sep 15, 2013 at 8:27
  • Check your connection strings again. I suspect you are on different databases (possibly on the same server) Commented Sep 15, 2013 at 8:29

2 Answers 2

27
SqlCommand cmd = new SqlCommand("proc_name", conn);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@p_SomeVal", SqlDbType.Int));
cmd.Parameters["@p_SomeVal"].Direction = ParameterDirection.Output;

rdr = cmd.ExecuteReader();
//...process rows...

rdr.Close();

if (cmd.Parameters["@p_SomeVal"].Value != null)
SomeVal = (int)cmd.Parameters["@p_SomeVal"].Value;

After procesing rows I added rdr.Close(); and worked fine.

Sign up to request clarification or add additional context in comments.

3 Comments

@Oded solution was simple :(
Or if you like one-liners you could do something like var SomeVal = command.Parameters["@p_SomeVal"].Value != null ? (int)command.Parameters["@p_SomeVal"].Value : default(int);
Sorry I was too hasty... null and DBNull... you will have to use this here var SomeVal = command.Parameters["@p_SomeVal"].Value is DBNull ? default(int) : (int)command.Parameters["@p_SomeVal"].Value;
4

Salaam, You can check if output is null and convert like this.

returnedSQLParameter.Value != DBNull.Value? (int)returnedSQLParameter.Value : 0;

Because it is returning DBNull.value when output sent NULL from stored procedure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.