SQL Server Optional Parameter Date from to - sql

I have a stored procedure and I want to search between the from and to date, but:
if #FromDate is not null and #ToDate is not null then
vSaleDetail.date between #FromDate and #ToDate
if #FromDate is not null and #ToDate is null then
vSaleDetail.date = #FromDate
if #FromDate is null and #ToDate is then
Return All
This is what I have but it is not working
where
(((#FromDate is null and #ToDate is null) OR (vSaleDetail.date between #FromDate and #ToDate ))
AND ((#FromDate is null) OR (vSaleDetail.date = #FromDate)))
Please help — what do I need to do to fix it?

I would poulate the null parameters with dates way outside the range you need. So If form date is null, I would populate with the earlies t accepatable date in your database's datetime data type. The To date would be poulated with the latest possible date. Then you don't need to use all that complex logic which slows things down.
IF #FromDate is null
Begin
Set #Fromdate = '17530101'
END
IF #ToDATE is null
BEGIN
SET #Todate = '99991231'
END
select ...
WHERE vSaleDetail.date >=#FromDate and <= #ToDate

You can try this:
WHERE (vSaleDetail.date BETWEEN #FromDate AND ISNULL(#ToDate,#FromDate)
OR COALESCE(#FromDate, #ToDate) IS NULL)
ISNULL(p1, p2):
if p1 IS NULL then p2 is returned, otherwise p1 is returned
COALESCE(p1, p2, ...):
Like ISNULL(). returns p1 unless it is NULL, in which case, p2 is returned unless it is NULL, in which case p3.... if all parameters in COALESCE() are null, NULL is returned.

Try this:
WHERE
(
( #FromDate IS NULL AND #ToDate IS NULL)
OR
( vSaleDetail.date BETWEEN #FromDate AND #ToDate )
)
OR <-- #FromDate IS NULL AND #FromDate IS NULL
( #FromDate IS NULL OR vSaleDetail.date = #FromDate )

declare #default_min_date datetime;
declare #default_max_date datetime;
SET #default_min_date = 0
SET #default_max_date = 2958463;
SELECT *
FROM MyTable
WHERE
myDateColumn >= Isnull(#DateFrom, #default_min_date) AND myDateColumn <= Isnull(#DateTo, #default_max_date)

AND (#DateFrom IS NULL OR CONVERT(DATETIME, [CreationDate], 103) BETWEEN CONVERT(DATETIME, #DateFrom, 103) AND DATEADD(DAY, 1, CONVERT(DATETIME, ISNULL(#DateTo, #DateFrom), 103)))

Related

Conversion of Date in SQL Server

I am trying to make a comparison on the basis of CreatedDate but it gives me an error like
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
here is my query as #startdate and #endDate are my parameters for the Stored procedure.
declare #startDate as varchar(100) = null
declare #endDate as varchar(100) = null
set #startDate = '01/11/2016'
set #endDate = '30/11/2016'
SELECT CreatedDate FROM Table1
WHERE HCCreatedDate BETWEEN
CONVERT(Datetime, ISNULL(#startDate,''), 103)
AND CONVERT(Datetime, ISNULL(#endDate,''), 103)
Please convert the HCCreatedDate column as below
declare #startDate as varchar(100) = null
declare #endDate as varchar(100) = null
set #startDate = '01/11/2016'
set #endDate = '30/11/2016'
SELECT
CreatedDate
FROM
Table1
WHERE
CONVERT(DATETIME,HCCreatedDate,103) BETWEEN CONVERT(DATETIME, ISNULL(#startDate,''), 103) AND CONVERT(DATETIME, ISNULL(#endDate,''), 103)
Also Conver your column into Datetime. and try again
declare #startDate as varchar(100) = null
declare #endDate as varchar(100) = null
set #startDate = '01/11/2016'
set #endDate = '30/11/2016'
SELECT CreatedDate FROM Table1
WHERE CONVERT(DATETIME, HCCreatedDate), 103)BETWEEN
CONVERT(DATETIME, ISNULL(#startDate,''), 103)
AND CONVERT(DATETIME, ISNULL(#endDate,''), 103)

Stored procedure returns no records when datetime filters are NULL?

Consider this stored procedure :
CREATE PROCEDURE [dbo].[sp_getclients]
#FromDate datetime, #ToDate datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM CM.Clients
--If both dates are not NULL then also check PurchaseDate to be between them
WHERE
(#FromDate IS NOT NULL AND #ToDate IS NOT NULL
AND Clients.PurchaseDate >= #FromDate
AND Clients.PurchaseDate <= #ToDate)
OR
--If #FromDate is not NULL AND #ToDate IS NULL then also check PurchaseDate to be greater than #FromDate
(#FromDate IS NOT NULL AND #ToDate IS NULL
AND Clients.PurchaseDate >= #FromDate)
OR
--If #FromDate is NULL AND #ToDate IS NOT NULL then also check Trans_Date to be less than #ToDate
(#FromDate IS NULL AND #ToDate IS NOT NULL
AND Clients.PurchaseDate <= #ToDate)
END
When I execute this stored procedure with NULL parameters, no records are returned.
Any idea where I did go wrong here?
Add this:
OR
(#FromDate IS NULL AND #ToDate IS NULL)

How can I include null values in BETWEEN clause?

In my query's where clause I have the condition:
User.DateOfBirth BETWEEN #startDate AND #endDate
Where #startDate and #endDate are nullable. If #startDate is null, I want all values less than or equal to #endDate; if #endDate is null, I want all values greater than or equal to #startDate; if both are null I want all values.
My failed attempt - returns 0 results
((( User.DateOfBirth > #startDate) OR (#startDate Is null)) AND (( User.DateOfBirth < #endDate) OR (#endDate is null)) )
(Editor's note: BETWEEN includes the end points (less/greater than or equal), but the description for the null cases didn't. I've assumed this is an oversight.
Try this:
[User].DateOfBirth BETWEEN ISNULL(#startDate,[User].DateOfBirth) AND ISNULL(#endDate,[User].DateOfBirth)
Two approaches spring to mind:
Tread the four cases separately and then OR them together:
start and end are null: any date matches,
start is null, so need DoB <= end
send is null, so need DoB >= start
neither is null, so need between
This will lead to a long expression.
Use IsNull:
As shown by mehdi lotfi in his answer.
If you are using a nullable datetime type you could use
User.DateOfBirth BETWEEN isnull(#startDAte, CAST('1753-01-01' AS datetime)) AND isnull(#endDAte, CAST('9999-12-31' AS datetime))
for datetime2 use
User.DateOfBirth BETWEEN isnull(#startDAte, CAST('0001-01-01' AS datetime2)) AND isnull(#endDAte, CAST('9999-12-31' AS datetime2))
WHERE
((User.DateOfBirth BETWEEN #startDAte AND #endDAte) AND #startDAte is not null AND #endDAte is not null)
OR
((User.DateOfBirth =< #endDAte) AND #startDAte is null AND #endDAte is not null)
OR
((User.DateOfBirth >= #startDAte) AND #startDAte is not null AND #endDAte is null)
OR
(1=1 AND #startDAte is null AND #endDAte is null)
Try this:
select * from yourtable
where
(#startdate is null and #enddate is null)
or
(#startdate is null and #enddate is not null and User.DateOfBirth <= #enddate)
or
(#startdate is not null and #enddate is null and User.DateOfBirth >= #startdate)
or
(#startdate is not null and #enddate is not null and User.DateOfBirth BETWEEN #startdate AND #enddate)
This addresses all possible cases:
Both parameters are null - return all results
Non null end date only - return all results where DOB <= end date
Non null start date only - return all results where DOB >= start date
Both parameters are non null - return all results where DOB is between start and end dates

condition in where clause with optional parameter

There are thee input parameter in my stored procedure. for example,
DECLARE #fromDate DateTime = NULL
DECLARE #toDate DateTime = NULL
DECLARE #Id int = NULL
I want to write a condition in where clause like...if fromDate is provided then searching must be done on #fromDate. if #fromDate is not provided then check for #Id variable if this is not null then search basis on #Id...
Something like...
where
CASE
when #fromDate is not null
THEN (#FromDate is null or ([Created] between #FromDate and #ToDate))
ELSE (#requestId is null or Id=#requestId)
there is one problem with below solution...if #fromDate and #Id both are provided then this will do intesect of them and nothing is return.....condition should be like...if #fromDate is given the priority gives to #fromDate even if #Id is provided and result must not be dependend to #Id parameter....
Because you depend on both parameters you than can use them both in condition:
where
(#FromDate is null or ([Created] between #FromDate and #ToDate))
or
((#requestId is null or Id=#requestId)
and #FromDate is null) ----mix #requestId & #FromDate
Do you mean this? Please check:
WHERE [Created] BETWEEN
(CASE WHEN #FromDate IS NOT NULL THEN #FromDate ELSE [Created] END) AND
(CASE WHEN #ToDate IS NOT NULL THEN #ToDate ELSE [Created] END) AND
Id=(CASE WHEN #requestId IS NOT NULL THEN #requestId ELSE Id END)

Determine if two parameters are null, then use parameters in the where clause

Good day, I receive 2 nullable date parameters in my stored procedure. #StartDate and #EndDate. I need to execute my procedure as normal if these two parameters are NULL, else the #StartDate param needs to be >= my StartDateTime value AND #EndDate param needs to be <= my EndDateTime value.
Below is a snippet of what I am trying to accomplish but are not sure of the syntax.
FROM DI_Intervention_Schedule S
WHERE
(
#ID IS NULL
OR S.[ID] = #ID
)
AND (
CASE #StartDate WHEN IS NOT NULL THEN
#StartDate >= S.[StartDateTime] AND #EndDate <= S.[EndDateTime]
END
)
Any help please?
Try below code :
FROM DI_Intervention_Schedule S
WHERE
(S.[ID] = #ID OR #ID IS NULL)
AND (( S.[StartDateTime] >= #StartDate AND S.[EndDateTime] <= #EndDate) OR #StartDate IS NULL )