tags:

views:

20

answers:

2

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
+1  A: 

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
Baaju
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.
Joel Coehoorn
A: 

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
Kyra
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.
Kyra
@User228777 yes unfortunately there is no way to do this.
Baaju
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