0

I have a stored procedure in SQL Server. I want to set default value when null is passed; otherwise, use the passed value. However, I am not sure if my code reflects the behavior I want. If not, what should I do?

CREATE PROCEDURE [dbo].[test]
    (@PassedTableName nvarchar(100)) 
AS
BEGIN
    DECLARE @TableName AS NVarchar(255) = 'defaultTablenName'

    SELECT @TableName = QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME = @PassedTableName 

    DECLARE @sql0 AS NVARCHAR(MAX)
    SELECT @sql0 = 'select count(*) from ' + @TableName 
    EXEC(@SQL0)
7
  • 1
    I cannot figure out what you are trying to do here. Commented Oct 18, 2017 at 14:03
  • 1
    select @TableName = isnull(QUOTENAME( TABLE_NAME ), 'defaultTablenName') Commented Oct 18, 2017 at 14:04
  • Are you trying to set optional parameters or just send a NULL to the parameter? Commented Oct 18, 2017 at 14:04
  • @YogeshSharma, that's my first idea too, but will it work if the select returns no row at all? Commented Oct 18, 2017 at 14:08
  • Just change @end WHERE TABLE_NAME = ISNULL(@PassedTableName, TableName) Commented Oct 18, 2017 at 14:15

2 Answers 2

3

Just specify the default value when the parameter is declared:

CREATE PROCEDURE [dbo].[test]
    (@PassedTableName nvarchar(100) = 'defaultTableName') 

If the user passes in a parameter, it will use it. If they exclude the parameter, it will default to defaultTableName.

One warning, though. If the user includes the parameter but explicitly specifies NULL (by calling dbo.test @PassedTableName = NULL), the value will be NULL. In that case, I'd recommend:

CREATE PROCEDURE [dbo].[test]
    (@PassedTableName nvarchar(100) = NULL) 

IF @PassedTableName IS NULL 
SET @PassedTableName = 'defaultTableName'
Sign up to request clarification or add additional context in comments.

2 Comments

should the declaration not use 'defaultTableName' in stead of null ?
@GuidoG sounds right, the original example was a little vague.
2

You can do this by using COALESCE or by specifiying the default value when the parameter is declared.

CREATE PROCEDURE [dbo].[test]
    (@PassedTableName nvarchar(100) = 'defaultTableName') 

or

DO STUFF WHERE tablename = COALESCE(@PassedTableName,'defaultTableName')

Either will work. There's another way by using IF

IF @PassedTableName IS NULL
  SET @PassedTableName = 'defaultTableName';

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.