dev.net
dev.net

Reputation: 5

How to write filtered queries using SQL stored procedures?

How can I write a SQL stored procedure where I want the parameters to be optional in the select statement?

Upvotes: 0

Views: 1147

Answers (1)

Charles Bretana
Charles Bretana

Reputation: 146419

try this.. Make the SPs input parameters that control the filtering optional, witrh default values of null. In each select statement's Where clause, write the predicate like this:

  Create procedure MyProcedure
  @columnNameValue [datatype] = null
  As

      Select [stuff....]
      From table
      Where ColumnName = Coalesce(@columnNameValue , ColumnName)

this way if you do not include the parameter, or if you pass a null value for the parameter, the select statement will filter on where the column value is equal to itself, (effectively doing no filtering at all on that column.)

The only negative to this is that it prevents you from being able to pass a null as a meaningfull value to explicitly filter on only the nulls.... (i.e., Select only the rows where the value is null) Once the above technique has been adopted, you would need to add another parameter to implement that type of requirement. ( say, @GetOnlyNulls TinyInt = 0, or something similar)

  Create procedure MyProcedure
  @columnNameValue [datatype] = null,
  @GetOnlyNulls Tinyint = 0
  As

      Select [stuff....]
      From table
      Where (ColumnName Is Null And @GetOnlyNulls = 1)
            Or ColumnName = Coalesce(@columnNameValue , ColumnName)

Upvotes: 4

Related Questions