2

I'm having trouble with the output parameter of a stored procedure that's being executed inside the while loop of a cursor.

DECLARE @p_in int
DECLARE @p_out char

OPEN crs_clientId

FETCH NEXT FROM crs_clientId INTO @p_in

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @p_in

    EXEC dbo.usp_get_letter_for_number
             @in = @p_in, @out = @p_out OUTPUT;

    PRINT @p_out

    FETCH NEXT FROM crs_clientId INTO @p_in
END

CLOSE crs_clientId
DEALLOCATE crs_clientId

If I run this stored procedure independently, I get:

1
A
2
B
3
C

However, running it within the the cursor I get:

1
A
2
A
3
A

What am I missing? Why is the stored procedure only updating @p_out on the first pass?

1
  • sorry, that was a typo. The end of the loop is FETCH NEXT FROM crs_clientId INTO @p_in Commented Jan 22, 2018 at 20:04

2 Answers 2

2

Still not sure what exactly the problem was, but the fix was to set the @p_out to null at the beginning of each pass of the cursor. For some reason, if the @p_out wasn't null, the output of the stored procedure wouldn't write to it.

The loop now looks like this and works correctly:

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @p_in
    SET @p_out = NULL;

    EXEC dbo.usp_get_letter_for_number
         @in = @p_in, @out = @p_out output

    PRINT @p_out

    FETCH NEXT FROM crs_clientId INTO @p_in
END
Sign up to request clarification or add additional context in comments.

Comments

0

I am not sure how are you getting 1,2,3,4 in output. As code seems to have issue.

You are assigning a value to cursor in the end which seems incorrect variable

See @c_clientId in FETCH NEXT

So maybe your have posted half code.

Or you need to assign value to correct varable i.e. @p_in in end of cursor loop to get correct value

I tried to simulate with a sample procedure to return values

--sample stored procedure
create procedure usp_get_letter_for_number(@in int, @out char(1) OUTPUT)
as
begin
    if @in = 1
        set @out = 'A'
    else if @in = 2
        set @out = 'B'
    else if @in = 3
        set @out =  'C'
    else 
        set @out = 'Z'
end

And used your code and corrected it to use @pin instead of @c_clientId with sample SELECT statement

DECLARE @p_in int
DECLARE @p_out char
DECLARE crs_clientId CURSOR FOR SELECT top 10 id from Users /*Sample sql query*/
OPEN crs_clientId

FETCH NEXT FROM crs_clientId INTO @p_in

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @p_in

    EXEC dbo.usp_get_letter_for_number
             @in = @p_in, @out = @p_out output

    PRINT @p_out

    FETCH NEXT FROM crs_clientId INTO @p_in
END

CLOSE crs_clientId
DEALLOCATE crs_clientId

Output

1
A
2
B
3
C
4
Z
5
Z
:
:

1 Comment

Sorry, that was a typo. I've fixed it.

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.