sql server optional parameters: syntax for between clause - sql-server

#FromDate datetime = null
#ToDate datetime = null
SELECT * FROM TABLE
WHERE ....
AND [PI].Date BETWEEN #FromDate AND #ToDate
When any date is null, the records are not displayed. What is the correct syntax so that I can get all records if any of the dates are null.
I have thought of this:
#FromDate datetime = '01/01/1901',
#ToDate datetime = '12/31/9999'
Thanks.

Try something like
SELECT * FROM TABLE
WHERE ....
AND [PI].Date BETWEEN ISNULL(#FromDate, [PI].Date) AND ISNULL(#ToDate, [PI].Date)

you can always default the date values to some extreme value and make sure an index is used:
SELECT
*
FROM TABLE
WHERE ....
AND [PI].Date BETWEEN ISNULL(#FromDate,convert(datetime,'1/1/1800'))
AND ISNULL(#ToDate, convert(datetime,'1/1/2500'))

You can try something like this:
#FromDate datetime = null
#ToDate datetime = null
SELECT * FROM TABLE
WHERE ....
AND [PI].Date BETWEEN CASE WHEN #FromDate is null THEN '01/01/1901' ELSE #FromDate END AND
CASE WHEN #ToDate is null THEN '12/31/9999' ELSE #ToDate END
HTH

SELECT * FROM [PI]
WHERE ([PI].Date >= #FromDate OR #FromDate IS NULL)
AND ([PI].Date <= #ToDate OR #ToDate IS NULL)

Related

Querying null datetime field with parameters

I have a table on my database (SQL Server 2016):
ID (numeric(10,0), not null)
Price (numeric(12,2), not null)
StartDate (datetime, null)
EndDate (datetime, null)
(There are more fields, but this is enough to get the point across)
One particular record has 'NULL' values for StartDate and EndDate:
ID 15
Price 25
StartDate NULL
EndDate NULL
If I run the query:
SELECT * FROM [Table]
Then the record is return as expected
However the following query:
DECLARE #StartDate datetime = NULL
DECLARE #EndDate datetime = NULL
SELECT * FROM [Table]
WHERE StartDate = #StartDate AND EndDate = #EndDate
I get no records!
What am I missing?
The following does work, but it just 'feels' wrong!
DECLARE #StartDate datetime = NULL
DECLARE #EndDate datetime = NULL
SELECT * FROM [Table]
WHERE (StartDate = #StartDate OR (StartDate IS NULL AND #StartDate IS NULL))
AND (EndDate = #EndDate OR (EndDate IS NULL AND #EndDate IS NULL))
For context, the query will ultimately be run via a VB.Net application, but I'm getting this problem running the query via SSMS, so it's definitely a SQL issue.

find latest date between created date and updated date in sql stored procedure [duplicate]

This question already has answers here:
Selecting most recent date between two columns
(13 answers)
Closed 3 years ago.
I have two column in my table as created date and updated date.I want to find latest date from that.which ever is latest I want to considered that and filter it from input values.
My current query is :-
Select *
from Emp E
WHERE (E.USERID=#UserID) and (E.CDATE >= #FromDate AND E.CDATE <= #ToDate) order by qdate desc
You can subtract fromDate and toDate with system date to find the latest date. And by using case you can filter based on the latest date.
Like:
SELECT *
FROM Emp E
WHERE ( E.USERID = #UserID )
AND E.CDATE = CASE WHEN #fromdate - GETDATE() > #toDate - GETDATE()
THEN #fromdate
ELSE #toDate
END;
To find the latest date between two dates, you can use reference of the script below.
DECLARE #fromdate DATETIME, #toDate DATETIME, #date DATETIME
SET #fromdate = '2019-04-05'
SET #toDate = '2019-05-05'
SET #date = CASE WHEN #fromdate - GETDATE() > #toDate - GETDATE() THEN #fromdate
ELSE #toDate
END;
SELECT #date;
SELECT *
FROM Emp E
WHERE (E.USERID = #UserID)
AND 1 = CASE
WHEN E.CDATE >= E.UDATE
THEN CASE
WHEN (
E.CDATE >= #FromDate
AND E.CDATE <= #ToDate
)
THEN 1
END
WHEN E.CDATE < E.UDATE
THEN CASE
WHEN (
E.UDATE >= #FromDate
AND E.UDATE <= #ToDate
)
THEN 1
END
ELSE 0
END
assuming update date is UDATE
select *
from Emp E
where (E.USERID=#UserID)
and (SELECT MAX(V) from (values(E.CDATE), (E.UDATE)) MAX_DATE(V)) BETWEEN #FromDate AND #ToDate
declare #cdate smalldatetime,#udate smalldatetime
Select CDATE=max(CDATE ) ,UDATE =max(UDATE ) into #tbldate
from Emp
set #cdate =(select CDATE from #tbldate)
set #udate =(select udate from #tbldate)
if(#cdate>#udate)
begin
Select CDATE as Latest_Date from #tbldate
end
else
begin
Select UDATE as Latest_Date from #tbldate
end
//Run this by selecting all

Condition to COMPARE TWO DATE From parameter and ADD if it Satisfies

This is MY procedure , Im getting from and to date in the procedure
i have to check if difference between FROM and TO date is greater than 2
if the condition satisfies i have to add 2days in from days and set it as TODATE
ALTER PROCEDURE [dbo].[sp_TU_AvgStdDev_Report]
#FromDate as Datetime,
#ToDate as Datetime,
#RecipeCode as Varchar(8000),
#Grade as Varchar(10),
#WcID as Int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
IF (condition to check if #FromDate - #ToDate > 2)
--if it satisfies
SET #ToDate to #fromDate+2Days
Please help me in figuring it out...
You need to used date functions for this.
ALTER PROCEDURE [dbo].[sp_TU_AvgStdDev_Report]
#FromDate as Datetime,
#ToDate as Datetime,
#RecipeCode as Varchar(8000),
#Grade as Varchar(10),
#WcID as Int
AS
BEGIN
IF (datediff(day,#FromDate,#ToDate)>2)
SET #ToDate = DATEADD(day,2, #fromDate)
Use DATEDIFF and DATEADD Function
IF DATEDIFF(D,#FromDate,#ToDate) > 2
BEGIN
--if it satisfies
SET #ToDate = DATEADD(D,2, #fromDate)
END
You should have to use DateDiff
Use below query may be it helps you.
if( Datediff(day, Todate, FromDate) > 2)
// Your query
First remove the time part from date by converting it to date like
convert(date,convert(varchar,#FromDate))
convert(date,convert(varchar,#ToDate))
So then you will have only date and then you can find the difference between two date using DATEDIFF sql function
Final solution
IF DATEDIFF(day,convert(date,convert(varchar,#FromDate)),convert(date,convert(varchar,#ToDate))) > 2
BEGIN
--if it satisfies
SET #ToDate = DATEADD(day,2, convert(date,convert(varchar,#FromDate)))
END

How to subtract two date as datetime2 format in Sql Server 2008

How can I create a method to subtract two dates and this is equal to in real date as format datetime2(7) in sql server 2008.
For example ,I create this method:
Delete from TblMessage
Where MDateTime<((SELECT TOP (1)MDateTime FROM TblMessage ORDER BY MDateTime DESC)- ('2013-10-04 16:47:56.0000000'))
but it is not working .I want to result of subtract two date like this:
MDateTime1:2013-10-05 16:47:56.0000000
MDateTime2:2013-09-04 16:47:56.0000000
Result:2013-01-01 00:00:00.0000000
Result=MDateTime1-MDateTime2
How can I do this. Thanks...
Perhaps you are looking for this?
select DATEADD( day, datediff(day,GETDATE(), getdate() - 10), GETDATE() ) ;
DATEDIFF(dayofyear,MDateTime1,MDateTime2) AS Result
http://msdn.microsoft.com/en-us/library/ms189794.aspx
DECLARE
#DATE1 DATETIME = '2013-10-05 16:47:56.000',
#DATE2 DATETIME = '2013-09-04 17:37:42.000',
#DATEDIFF AS INT,
#BASEDATE DATETIME;
-- USE WHAT EVER DATE YOU WISH TO BE YOUR BASE DATE
SET #BASEDATE = '1/1/1900';
SET #DATEDIFF = DATEDIFF(SECOND, #DATE2, #DATE1);
SELECT #DATE1,#DATE2,#DATEDIFF, DATEADD(SECOND,#DATEDIFF,#BASEDATE)
Thus a scalar function could be created like this...
CREATE FUNCTION dbo.sf_GetMeasureDate
(
#EndDate DATETIME,
#StartDate DATETIME,
#BaseDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE #DATEDIFF AS INT
SET #DATEDIFF = DATEDIFF(SECOND, #StartDate, #EndDate);
Return DATEADD(SECOND,#DATEDIFF,#BASEDATE)
END
GO
Then within you regular SELECT statement you can call the function as such.
SELECT dbo.sf_GetMeasureDate('2013-10-05 16:47:56.000','2013-09-04 17:37:42.000','1/1/1900')
or within an existing query:
SELECT dbo.sf_GetMeasureDate([fld1],[fld2],'1/1/1900')

SQL server SP : #Param 's with sometime NULL values

I am very new to SQL Server Stored Procedures,
I am trying to create a SP that will give return a list of records in a table by filter via StartDate and EndDate , but there will be 'View All' Option so sometime those #Param might not contain any values.
Currently my SP is Like
CREATE PROCEDURE [dbo].[spGetBonusRun]
(
#StartDate as DATETIME,
#EndDate as DATETIME
)
AS
SELECT [Id]
,[StartDateTime]
,[EndDate]
,[Status]
FROM [Valt].[dbo].[BonusRun]
WHERE StartDateTime <= #StartDate AND EndDate >= #EndDate
How to active that ?
Try this:
WHERE (StartDateTime <= #StartDate OR #StartDate IS NULL) AND (EndDate >= #EndDate OR #EndDate IS NULL)
Hope it helps.
/Klaus
You can try something like this
CREATE PROCEDURE [dbo].[spGetBonusRun]
(
#StartDate as DATETIME,
#EndDate as DATETIME
)
AS
SELECT [Id]
,[StartDateTime]
,[EndDate]
,[Status]
FROM [Valt].[dbo].[BonusRun]
WHERE StartDateTime <= ISNULL(#StartDate, StartDateTime)
AND EndDate >= ISNULL(#EndDate, EndDate)
Note the use of ISNULL

Resources