简体   繁体   中英

Stored Procedure Where Clause Parameters

I've got an ASP.net search page where the user can enter one or more search criteria. The page calls a stored procedure to query a MS SQL Server 2008 db.

Part of the search criteria is single date or date range. If the user supplies Date1, we search on a single date. If the user supplies Date1 and Date2, we search on a date range.

My issue is coding this logic in the stored proc.

@Date1 datetime
@Date2 datetime
..other search params...

So there are three conditions:

  1. Both @Date1 and @Date2 are null (the user is not searching on dates)
  2. @Date1 is not null and @Date2 is null (the user is searching on a single date)
  3. @Date1 is not null and @Date2 is not null (user is searching a date range)

I can't figure out how to structure the WHERE clause to handle each of the three possible conditions.

I'm familiar with ISNULL() and COALESCE()

Any tips or suggestions are greatly appreciated.

CREATE PROCEDURE BLABLABLA(
  @DATE1 DATETIME = NULL,
  @DATE2 DATETIME = NULL
)
AS
BEGIN
  SELECT COL1, COL2
  FROM THE_TABLE
  WHERE 
    THE_TABLE.DATETIMEFIELD BETWEEN 
      ISNULL(@DATE1, THE_TABLE.DATETIMEFIELD) 
      AND COALESCE(@DATE2, @DATE1, THE_TABLE.DATETIMEFIELD)
END

Another choice, losing some expressiveness but likely using indexes, could be:

CREATE PROCEDURE BLABLABLA(
  @DATE1 DATETIME = NULL,
  @DATE2 DATETIME = NULL
)
AS
BEGIN
  SELECT COL1, COL2
  FROM THE_TABLE
  WHERE 
    (THE_TABLE.DATETIMEFIELD >= @DATE1 OR @DATE1 IS NULL) 
     AND (THE_TABLE.DATETIMEFIELD <= @DATE2 
         OR THE_TABLE.DATETIMEFIELD = @DATE1
         OR (@DATE1 IS NULL AND @DATE2 IS NULL)) 
END

You could try to create your SQL query as a string in the SP and then execute it, like this:

...
declare @sql varchar(500)
set @sql = 'select from myTable where 1=1'

if(@Date1 <> null)
    set @sql = @sql + ' and date1 >= '+ @date1

if(@Date2 <> null)
    set @sql = @sql + ' and date2 <= '+ @date2

print(@sql) -- for debug 
exec(@sql)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM