SQL in your SP is incorrect. You probably want
Select @code = RecItemCode from Receipt where RecTransaction = @id
In your application, you are not setting @code, you are trying to use it for the RecItemCode value. This will explain your NullReferenceException
when trying to use the output parameter, because the value is never assigned to it, and you get the default value.
Another problem is that your SQL statement, if rewritten as
Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id
This is a mix of variable assignment and data extraction. This highlights a couple of points. If you need data that @code controls in addition to other pieces of data, forget the output parameter and just select the data.
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
If you just need code, use the first SQL statement that I showed you. For random cases, you really need output and data, use two different operators
Select @code = RecItemCode from Receipt where RecTransaction = @id Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
This should assign your value to the output parameter, and also return two columns of data per row. However, this seems terribly redundant to me.
If you write your SP, as I showed at the very top, just call cmd.ExecuteNonQuery();
and then read the value of the output parameter.
Another issue with your SP and code. In your SP, you specified @code as varchar
. In your code, you indicate the parameter type as Int
. Either modify your SP, or your code to match types.
Also note: if everything you do returns one value, there is another way to do this that does not include output parameters at all. You can write
Select RecItemCode from Receipt where RecTransaction = @id
And then use object obj = cmd.ExecuteScalar();
to get the result, there is no need for the output parameter in SP or in your code.