0

I have a parameter for stored procedure, which I want to make optional and assign default value from a table, how do I do this?

ALTER PROCEDURE [DBO].[Test]

      @planId int = 1  ( This I can do )

But I would like to do

@planId int = ( Select Id from Table1 Where name = ‘ABC’) ‘ Assign default id from a table

2 Answers 2

3

If you want to do this, just assign 0 initially and in the first line of the procedure write this value into that variable.

ALTER PROCEDURE [DBO].[Test]
@planId int = 0
AS
BEGIN
SET @planId = ( Select Id from Table1 Where name = ‘ABC’)
...
...
...
END
Sign up to request clarification or add additional context in comments.

1 Comment

I'd use NULL rather than 0 for the default, and then don't for get to check that it's NULL before setting it.
1

Within the stored procedure you can declare and set the value. In this case you can set @planId to whatever you want then in the body:

CREATE PROCEDURE procedureName
    @planId int = null output
AS
    IF @planId = null
      Begin
      SET @planId = ( Select Id from Table1 Where name = ‘ABC’) 
      End
    ELSE --> then they gave you the value

4 Comments

This is how I am doing right now, so there is no way I can assign default ( select from a table) value at declaration. - Thanks
Really. I added a bit more to the beginning of my example. I have something basically the same and it sets the value.
@User228777 yes unfortunately there is no way to do this.
Kyra and Baaju, I know to pass Null and do the checking in stored proc code and handle accordingly, I thought it would be nice if I assign defalut value at declaration, but as you said I can not do this. I will use my current stored proc the way it is. -- Thanks

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.