4

I'm trying to determine why a db call in .Net is failing with an output parameter. I'm using Dapper ORM to make the call and this is a bare bones sample of the trace. It uses sp_executesql to parametrize the call and I think there lies the problem with the output parameter.

Consider this code:

CREATE PROC test
    @addressId INT = NULL OUTPUT
AS
    -- using select and set to see if if makes a difference using either
    select @addressId = 1
    SET @addressId = 1
GO

declare @p3 int
set @p3=NULL
exec sp_executesql N'test',N'@addressId int output',@addressId=@p3 output
select @p3

I would expect select @p3 to return 1, why does it return null?

2
  • 2
    Why are you using dynamic sql here? This should be a straight forward stored procedure call....no dynamic sql needed. Commented Apr 20, 2016 at 19:35
  • It was an output for one of the traces. I'm wondering now if it was a sqlText (instead of proc) call which caused that kind of sql. I've got it working now using another method. Commented Apr 21, 2016 at 10:03

2 Answers 2

3

You need to explicitly declare @addressId as an output parameter in the stored procedure call in exactly the same way you would if you weren't using dynamic SQL:

declare @p3 int
set @p3=NULL
exec sp_executesql N'EXEC test @addressId=@addressId OUTPUT',N'@addressId int output',@addressId=@p3 output
select @p3

Without dynamic SQL, the code would have to be:

declare @p3 int
set @p3=NULL
EXEC test @addressId=@p3 OUTPUT
select @p3
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response. The app is sending the sql correctly now and the traces looks like the second example in your answer. At least I know now what was missing from the original trace to make it work as expected.
0

As mentioned, the problem is that the dynamic SQL isn't actually passing the parameter through.

However, in this instance, you don't actually need dynamic SQL at all.

declare @p3 int;
exec test @addressId=@p3 output;
select @p3;

Furthermore, it's highly likely that you were simply using SqlCommand incorrectly.

SqlCommand.CommandType defaults to CommandType.Text which explains why the above code was generated, as it expects that the text is an SQL batch rather than the name of a stored procedure. No error was generated because it's valid to call a procedure without using the keyword EXEC.

If you use CommandType.StoredProcedure then everything should just work.

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.