1

Saw this on a test- My SQL experience is basic CRUD-related and I'm not sure what the intent of this would be, if any?

CREATE PROCEDURE [dbo].[uspGetAccountID]
(
        @AccountID int = 1
)
AS
        SELECT @AccountID 
GO 

What will be the output if the procedure is called as follows, and why?

exec dbo.uspGetAccountID 5

5
  • 2
    The result would be 5. @AccountID int = 1 setting a default value. So if you run you proc with 5 will return 5.
    – kostas ch.
    Jun 18, 2013 at 8:54
  • Indeed there is nonsense of this proc BUT it may used to had sense before changes occured and made it at this current state.
    – kostas ch.
    Jun 18, 2013 at 8:57
  • That was the obvious answer to me, but I ran it in Management Studio and it returned 0. Bigger question then became the intent for such a statement. Jun 18, 2013 at 9:01
  • 1
    Yeah, of course it's 5. gbn explains the most probable reason why you might have mistaken it for zero. Here is the sqlfiddle sqlfiddle.com/#!6/cfa39/1 Jun 18, 2013 at 9:47
  • It doesn't deserve a down vote because it does show SSMS can bollix you up.
    – gbn
    Jun 18, 2013 at 9:58

4 Answers 4

4

The zero is not the result of the code, it is the return value

SSMS actually generates this

USE [MyDB]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[uspGetAccountID] 
        @AccountID = 5

SELECT  'Return Value' = @return_value

GO

So you would have had 2 result sets. One for code, one for the return code

Add a RETURN 42 to the code in the procedure after the SELECT, you get 42 in the second result...

1
  • Thanks. I figured this was either a stupidly trivial exercise or was looking at some subtlety that I was unaware of. Jun 18, 2013 at 10:32
0

The result will be 5.

Default values on parameters are only assigned if no value has been provided.

You can create a stored procedure with optional parameters by specifying a default value for optional parameters. When the stored procedure is executed, the default value is used if no other value has been specified.

MSDN Article

0

Looks like a test stored procedure. It takes a parameter called @AccountID with a default value of 1.

exec dbo.uspGetAccountID 5

Would result in 5 being selected.

0
exec [dbo].[uspGetAccountID] 
-- should result in 1
exec [dbo].[uspGetAccountID] 5
-- should result in 5

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.