Re: Using CASE statement to build different where clause
From: Erland Sommarskog (sommar_at_algonet.se)
Date: 03/16/04
- Next message: MJJ: "Re: New to MSDE and SQL server"
- Previous message: Hugo Kornelis: "Re: Using CASE statement to build different where clause"
- In reply to: NWx: "Using CASE statement to build different where clause"
- Next in thread: NWx: "Re: Using CASE statement to build different where clause"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 16 Mar 2004 23:57:20 +0000 (UTC)
NWx (test@test.com) writes:
> Is it possible to use CASE statement to select a different where clause
> in a SQL statement?
There is no CASE statement in SQL Server, but there is a CASE expression.
> I want to create a stored proc, which can receive two parameters, start
> and end date
> If parameters are present (not null I suppose), I want to select records
> between those dates.
> Otherwise I want to select all records
WHERE date BETWEEN CASE WHEN @startdate IS NOT NULL
THEN @startdate
ELSE '19000101'
END AND
CASE WHEN @enddate IS NOT NULL
THEN @enddate
ELSE '20500101'
END
Or shorter:
WHERE date BETWEEN coalesce(@startdate, '19000101') AND
coalesce(@enddate, '20500101')
coalesce is in fact just a shortcut for the CASE expression above.
-- Erland Sommarskog, SQL Server MVP, sommar@algonet.se Books Online for SQL Server SP3 at http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp
- Next message: MJJ: "Re: New to MSDE and SQL server"
- Previous message: Hugo Kornelis: "Re: Using CASE statement to build different where clause"
- In reply to: NWx: "Using CASE statement to build different where clause"
- Next in thread: NWx: "Re: Using CASE statement to build different where clause"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|