0

Is it possible to build a dynamic where clause in a stored procedure such that if the parameter is empty, you select all item in the table? However, if you do have a parameter, you select items where the condition is true?

4
  • WHERE (@parameter IS NULL OR col = @parameter) Commented Sep 29, 2015 at 2:40
  • You can do it dynamically or with a simple where clause: where (@id is null or id = @id). Commented Sep 29, 2015 at 2:40
  • if i have a procedure called test and I want to select all, would I do call test(null)? Commented Sep 29, 2015 at 2:48
  • if i do call test(), it would say incorrect number of arguments Commented Sep 29, 2015 at 2:49

1 Answer 1

2

Here is the trick... you can create a string query for your select command, and then manipulate it by conditional statement.. see sample below.. hope you can apply the logic on your work.

    -- Put a default value `NULL` to your parameter first
    CREATE TABLE TableNameHere 
    (
      @ParameterName VARCHAR(MAX) = NULL
    )

    DECLARE @SQLQuery VARCHAR(MAX)

    --Initialize SQL statement first
    --It will return true always , therefor it will display all data
    SET @SQLQuery = 'SELECT * FROM TableNameHere WHERE 1 = 1' 

    -- If parameter has a value then do the where condition inside the block
    IF @ParameterName IS NOT NULL
        BEGIN
           SET @SQLQuery = @SQLQuery + ' AND ColumnNameHere = ''' + @ParameterName + ''''
        END

    EXEC(@SQLQuery)
Sign up to request clarification or add additional context in comments.

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.