How to use BETWEEN for datetime stored procedure - sql-server-2008

I am creating a stored procedure for searching. DateOrdered is column name in table of datetime type.
The problem is that I want to perform search on this column. The user can search on start date and end date. Also user can send null for any parameter, like start date or end date.
When the user will not send the start date or end date, I shall search on another option. My problem is that how can I handle this below is the query I tried, but without success
SELECT
#C_Order_ID = C_Order_ID
FROM
C_Order COrder
WHERE
(#AD_Org_ID IS NULL OR
COrder.AD_Org_ID IN (SELECT ID FROM fnSplitter(#AD_Org_ID)))
AND (#AD_Client_ID IS NULL OR
#AD_Client_ID IN (SELECT ID FROM fnSplitter(#AD_Client_ID)))
AND (#IsActive IS NULL OR COrder.IsActive = #IsActive)
AND (#startDate IS NULL OR
COrder.DateOrdered = #startDate BETWEEN #EndDate IS NULL
OR COrder.DateOrdered = #EndDate)
Thanks for your reply .

You may try like this:
COrder.DateOrdered BETWEEN #startDate AND #EndDate
So your query would be like
SELECT #C_Order_ID= C_Order_ID FROM C_Order COrder
WHERE
(#AD_Org_ID IS NULL OR COrder.AD_Org_ID IN (Select ID From fnSplitter(#AD_Org_ID)))
AND (#AD_Client_ID IS NULL OR #AD_Client_ID IN (Select ID From fnSplitter(#AD_Client_ID)))
AND (#IsActive IS NULL OR COrder.IsActive = #IsActive)
AND (#startDate IS NULL OR COrder.DateOrdered BETWEEN isnull(#startDate,'') AND isnull(#EndDate,''))
or better
SELECT #C_Order_ID= C_Order_ID FROM C_Order COrder
WHERE
(#AD_Org_ID IS NULL OR COrder.AD_Org_ID IN (Select ID From fnSplitter(#AD_Org_ID)))
AND (#AD_Client_ID IS NULL OR #AD_Client_ID IN (Select ID From fnSplitter(#AD_Client_ID)))
AND (#IsActive IS NULL OR COrder.IsActive = #IsActive)
AND (CAST(#startDate AS DATE) IS NULL OR (CAST(#startDate AS DATE) IS NULL OR CAST(COrder.DateOrdered AS DATE) >=CAST(#startDate AS DATE))
AND (CAST(#endDate AS DATE) IS NULL OR CAST(COrder.DateOrdered AS DATE) <=CAST(#endDate AS DATE))

SELECT #C_Order_ID= C_Order_ID FROM C_Order COrder
WHERE
(#AD_Org_ID IS NULL OR COrder.AD_Org_ID IN (Select ID From fnSplitter(#AD_Org_ID)))
AND (#AD_Client_ID IS NULL OR #AD_Client_ID IN (Select ID From fnSplitter(#AD_Client_ID)))
AND (#IsActive IS NULL OR COrder.IsActive = #IsActive)
AND (#startDate IS NULL OR COrder.DateOrdered BETWEEN #startDate AND #EndDate
OR COrder.DateOrdered = #EndDate)

Aaron Bertrand has written a good article about using BETWEEN with date ranges - What do BETWEEN and the devil have in common?, this is worth a read. Also it looks like you are passing a comma separated list in a string, then splitting it with a function fnsplitter, you may want to consider using table-valued paramters
However, to actually answer your question you can use the above idea of not using between and change your query to:
AND (#startDate IS NULL OR COrder.DateOrdered >= #startDate)
AND (#EndDate IS NULL OR COrder.DateOrdered <= #EndDate)
So you have 4 permutations.
Both #StartDate and #EndDate are null - returns all dates
#StartDate is not null and #EndDate is null - returns all dates after #StartDate
#StartDate is null and #EndDate is not null - returns all dates before #EndDate
Both #StartDate and #EndDate are not null - returns all dates between #StartDate and #EndDate
Based on your comments on another answer, it sounds like you may be passing a date as the #EndDate parameter, e.g. 2014-08-28, but still want to include all records on that date, even if they have a time associated, e.g. 2014-08-28 12:00, this is exactly why BETWEEN is not used for date ranges, instead you need to use the less than operator and add 1 day to your End date:
AND (#startDate IS NULL OR COrder.DateOrdered >= #startDate)
AND (#EndDate IS NULL OR COrder.DateOrdered < DATEADD(DAY, 1, #EndDate))

Related

SSRS String -vs- Data Integer

I am working on a SSRS report and using a parameter that allows you to choose multiple options. However, when I do this I get an error that states:
Error Converting Data Type nVarChar to Int.
The data in the database is an Integer. The parameter is set up as an Integer and it works great when only choosing one option. The issue comes when I choose multiple options.
My co-worker came up with one work-around but I would like something a little more elegant and easier to plug in if possible.
Here is his work-around:
ALTER PROCEDURE [dbo].[DtaPrep_MktgClients]
#BegDate date = NULL
, #EndDate date = NULL
, #Species varchar(50) = 'canine,feline,K9,'
 , #HospList varchar(500) = NULL
This is where the hospmastid string gets converted into a temp table
/*
--===================================--
HOSPITALS SETUP
--===================================--
*/
If #HospList IS NOT NULL
BEGIN
DECLARE #WorkHospList varchar(500)
SET #WorkHospList = #HospList
;
CREATE TABLE #HospList
( HospID smallint NULL )
SET #CommaLoc = charindex(',', #WorkHospList)
WHILE #CommaLoc > 1
BEGIN
SET #curVal = LEFT(#WorkHospList, #commaloc-1 )
INSERT INTO
#HospList( HospID )
SELECT #curVal
SET #WorkHospList = substring( #WorkHospList, #commaloc+1, len(#WorkHospList) )
SET #CommaLoc = charindex(',', #WorkHospList)
END
END
This is using the temp table to accomplish the same thing as a “WHERE Hospmastid IN (101,102,103)…”
Method 1
SELECT
HospitalMasterID
, ClientID
, FirstName
, LastName
FROM
Client
WHERE
HospitalMasterID IN (Select HospID From #HospList )
Needless to say, I am sure there is a better way to accomplish this. If anyone has any ideas, please let me know.
Here is the full Query I am now using. But it is not selecting anything so there is an issue with the Created Table.
USE [xxxxx]
GO
/****** Object: StoredProcedure [dbo].[PriceErosion] Script Date: 11/26/2013 8:26:33 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-- =============================================
-- Author:
-- Create date: 11/25/2013
-- Description: Determines the products in which the price was lowered and revenue lost during a set time period.
-- =============================================
*/
--#StartDate as Date = Null
--,#EndDate as Date = Null
--,#CurDate as Date = Null
--,#Hospital as VarChar = Null
--,#Division as Int = Null
Declare #StartDate as Date = Null
Declare #EndDate as Date = Null
Declare #Hospital as Int = Null
Declare #Division as Int = Null
DECLARE #curDate Date = Null
SET #curDate = GETDATE()
Set #StartDate = CASE WHEN #StartDate IS NULL THEN DATEADD(dd, -31, Dateadd(dd, -1, #curdate) ) ELSE #StartDate END
Set #EndDate = CASE WHEN #EndDate IS NULL THEN Dateadd(dd, -1, #curdate) ELSE #EndDate END
Set #Hospital = Case When #Hospital IS Null Then '3' Else #Hospital End;
IF OBJECT_ID('tempdb.dbo.#HospList') IS NOT NULL DROP TABLE #HospList ;
If #Hospital IS NOT NULL
BEGIN
DECLARE #WorkHospList varchar(500)
Declare #CommaLoc as Int
Declare #curVal as int
SET #WorkHospList = #Hospital
;
CREATE TABLE #HospList
( HospID smallint NULL )
SET #CommaLoc = charindex(',', #WorkHospList)
WHILE #CommaLoc > 1
BEGIN
SET #curVal = LEFT(#WorkHospList, #commaloc-1 )
INSERT INTO
#HospList( HospID )
SELECT #curVal
SET #WorkHospList = substring( #WorkHospList, #commaloc+1, len(#WorkHospList) )
SET #CommaLoc = charindex(',', #WorkHospList)
END
END
Begin
-- Sets the Baseline Price Date in the PriceChangeHistory Table.
With PC1
as
(Select
HospitalMasterID
,TxnCode
,UserInfoMasterID
,Active
,min(TxnDateTime) as StartingDate
From
PriceChangeHistory
Where
TxnDateTime Between #StartDate and #EndDate
Group By
HospitalMasterID, TxnCode, UserInfoMasterID, Active)
-- Gets the Baseline Price for the period from the PriceChangeHistory Table
,PC
as
(Select
PC1.HospitalMasterID
,PC1.TxnCode
,PC1.UserInfoMasterID
,PC1.Active
,Cast (PC1.StartingDate as Date) as StartingDate
,PC2.OldPrice as StartingPrice
,PC2.NewPrice
,PC2.TxnSubType
From
PC1
Inner Join
PriceChangeHistory as PC2
On
PC1.HospitalMasterID = PC2.HospitalMasterID
and
PC1.TxnCode = PC2.TxnCode
and
PC1.StartingDate = PC2.TxnDateTime
Where
PC2.OldPrice > PC2.NewPrice)
--MedicalHistory Information
,MH
as
(Select
HospitalMasterID
,PatientID
,TxnDate
,TxnCode
,Description
,ListAmount
,ExtendedAmount
,TxnType
,Quantity
,(Case
When Quantity <> '1' Then (ListAmount/Quantity)
Else ListAmount
End) as UnitPrice
From
MedicalHistory
Where
TxnDate Between #StartDate and #EndDate
and
_IsServOrITem = 1)
-- Determines the Revenue lost per each sale, also reduces the results to only those items where the Price was lowered not raised.
,RL
as
(Select
PC.HospitalMasterID
,MH.PatientID
,PC.TxnCode
,PC.TxnSubType
,MH.Description
,PC.UserInfoMasterID as ChangedByUserID
,MH.TxnDate
,PC.StartingPrice
,Cast (MH.UnitPrice as Money) as UnitPrice
,Cast ((StartingPrice - UnitPrice) as Money) as RevenueLost
From
PC
Left OUter Join
MH
on
PC.HospitalMasterID = MH.HospitalMasterID
and
PC.TxnCode = MH.TxnCode
Where
PC.StartingPrice > MH.UnitPrice)
--- Determine the name of the tech changing the prices.
,UI
as
(Select
HospitalMasterID
,UserInfoMasterID
,Name
From
UserInfo)
--- Get the Division and Hospital Name for each Hospital.
,HODI
as
(Select
DI.DivisionID
,DI.DivisionName
,HO.HospMastID
,HO.HospCode
,HO.HospName
From
ref_Hospital as HO
inner Join
ref_Division as DI
on
HO.DivisionID = DI.DivisionID)
,HI
as
(Select
HODI.DivisionID
,HODI.DivisionName
,RL.HospitalMasterID
,HODI.HospCode
,HODI.HospName
,RL.PatientID
,RL.TxnCode
,RL.TxnSubType
,RL.Description
,RL.ChangedByUserID
,RL.TxnDate
,RL.StartingPrice
,RL.UnitPrice
,RL.RevenueLost
From
RL
Left Outer Join
HODI
ON
RL.HospitalMasterID = HODI.HospMastID
Where
TXNDate Between #StartDate and #EndDate)
Select
*
From
HI
Where
HospitalMasterID in (Select HospID from #Hosplist)
Order By
HOspitalMasterID
end
Prior to SQL Server 2008, the standard way to filter by one or more values was to pass an XML document to the Stored Procedure and join on it. In this case, you could pass the data as a string with the integers separated by commas, then convert that into an XML document, then join on the XML. So you should change the multiselect in SSRS to a text datatype. Here's a post that shows you how to open an XML document: http://blog.sqlauthority.com/2009/02/13/sql-server-simple-example-of-reading-xml-file-using-t-sql/
SQL Server 2008 lets you use table-valued parameters, but again, it might be best to pass the data as a string of comma separated integers and then let the stored procedure put the data into a table-valued parameter, and then join on that. Here's a post that describes how to use table valued parameters: http://blog.sqlauthority.com/2008/08/31/sql-server-table-valued-parameters-in-sql-server-2008/

check date between two dates or NULL in sql

I want to check date in between two dates or can pass as a NULL
using stored proc
code
declare #fromDate date = null
declare #toDate date = null
select * from Mytable
where date betweeen #fromDate and #toDate OR NULL (how to check for both parameters)
I have other 2 more parameters so irrespective with date result should be displayed.
if #todate and #fromDate is NULL
please help.
Try with coalesce function as below
declare #fromDate date = null
declare #toDate date = null
select * from Mytable
where date between coalesce(#fromDate,date) and coalesce(#toDate,date)
Pretty much convert your English to SQL:
where (date is null or date betweeen #fromDate and #toDate)
When searching for a better solution than "between" with "coalesce" i found this thread:
firebird SQL
param is never NULL
createdatum is never NULL
offdatum can be NULL - for obvious reasons ;)
Initial solution:
where
X = :X
AND
cast(:QryDateTime as DATE) between
createdatum and coalesce(offdatum, cast(:QryDateTime as DATE))
problem there was a little tricky: when using "now" as value for QryDateTime there was (very rarely) no result found - even if there should exist one
Problem was that now is evaluated every time separately and obviously not in the left-to-right order.
I finally changed it to:
where
X = :X
AND
iif(offdatum is null, 1, iif(offdatum > cast(:QryDateTime as DATE), 1, 0)) = 1
AND
cast(:QryDateTime as DATE) > createdatum

How to give date range in a month & Year format in where clause sql server

I am trying to give date range in where clause like below.. however its not giving correct o/p
declare #StartDate DATETIME, #EndDate DATETIME
set #StartDate='9/01/2011'
set #EndDate='1/30/2012'
Select * from mytable Where MONTH(WT.ToDate) >= MONTH(#StartDate) AND MONTH(WT.ToDate) <=MONTH(#Enddate)
AND YEAR(WT.ToDate)>= YEAR(#StartDate) AND YEAR(WT.ToDate) <=YEAR(#Enddate)
Please help
What is WT.ToDate, What WT is referring to?
it should be.
declare #StartDate DATETIME, #EndDate DATETIME
set #StartDate='9/01/2011'
set #EndDate='1/30/2012'
Select * from mytable as WT Where MONTH(WT.ToDate) >= MONTH(#StartDate) AND MONTH(WT.ToDate) <=MONTH(#Enddate)
AND YEAR(WT.ToDate)>= YEAR(#StartDate) AND YEAR(WT.ToDate) <=YEAR(#Enddate)
Firstly, note I've changed the format you've specified the dates in to avoid any risk of misinterpretation (now yyyyMMdd).
Secondly, try a clause like this:
declare #StartDate DATETIME, #EndDate DATETIME
set #StartDate='20110901'
set #EndDate='20120130'
Select *
from mytable
Where WT.ToDate >= #StartDate AND WT.ToDate < #EndDate
Note, this will not return rows for 30 Jan 2012, so just tweak your #EndDate as appropriate

SSRS default parameter values in subscription

I have a report that has two required date parameters which the user enters. I want to create a subscription that runs on Friday that pulls for the previous week's Sunday through Saturday period. So for example, for this coming Friday, the subscription would pull for Jan 29 - Feb 4. I've tried =Now(), =Today(), #ExecutionTime and then subtracting the number of days but all I get is errors. Is this possible to do?
I did see this link but I wonder if there's a better way.
http://www.sqlservercentral.com/articles/Development/datadrivensubscriptions/2432/
SSRS 2008
Yes I have done this, see this post https://stackoverflow.com/a/5539615/168703
You can create a dataset that gets date ranges and use it in your report. Then your subscription can use this date range and change on its own dynamically without manual changes every day/week/month/year/etc.
Reposted here as well, this is your most flexible solution:
I'll also share a set of common date functions I use. Just create this as a table valued function:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
CREATE FUNCTION [dbo].[udfCommonDates] (#date datetime)
RETURNS #t table (week_start datetime,
week_end datetime,
lastweek_start datetime,
lastweek_end datetime,
month_start datetime,
month_end datetime,
lastmonth_start datetime,
lastmonth_end datetime,
yesterday_start datetime,
yesterday_end datetime,
today_start datetime,
today_end datetime,
thisweek_monday_start datetime,
thisweek_monday_end datetime,
year_start datetime,
year_end datetime,
tomorrow_noon datetime,
today_noon datetime,
date_only datetime)
BEGIN
INSERT #t
SELECT
dbo.get_week_start ( #date ) AS week_start,
dbo.get_week_end ( #date ) AS week_end,
dbo.get_week_start ( DATEADD(d, -7, #date ) ) AS lastweek_start,
dbo.get_week_end ( DATEADD(d, -7, #date ) ) AS lastweek_end,
dbo.get_month_start( #date ) AS month_start,
dbo.get_month_end ( #date ) AS month_end,
dbo.get_month_start ( DATEADD(m,-1, #date) ) AS lastmonth_start,
dbo.get_month_end ( DATEADD(m,-1,#date) ) AS lastmonth_end,
dbo.get_yesterday_start ( #date ) AS yesterday_start,
dbo.get_yesterday_end ( #date ) AS yesterday_end,
dbo.get_today_start (#date) AS today_start,
dbo.get_today_end ( #date ) AS today_end,
dbo.get_weekday_start(1,#date) AS thisweek_monday_start,
dbo.get_weekday_end(1,#date) AS thisweek_monday_end,
dbo.get_year_start(#date) AS year_start,
dbo.get_year_end(#date) AS year_end,
dbo.get_tomorrow_noon(#date) AS TomorrowNoon,
dbo.get_today_noon(#date) AS TodayNoon,
dbo.get_date_only(#date) AS DateOnly
RETURN
END
Here are the scalar valued functions for these:
CREATE FUNCTION [dbo].[get_date_only] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN dateadd(day, DateDiff(day, 0, GetDate()), 0)
END
GO
CREATE FUNCTION [dbo].[get_month_end] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN dateadd(ms, -3, dateadd (m,datediff(m,0,
dateadd(m,1,#date)),0))
END
GO
CREATE FUNCTION [dbo].[get_month_start] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN dateadd(m,datediff(m,0, #date),0)
END
GO
CREATE FUNCTION [dbo].[get_today_end] (#today datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
return dateadd(ms, -3, datediff(d,0,dateadd(d,1,#today)))
END
GO
CREATE FUNCTION [dbo].[get_today_noon](#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
RETURN DATEADD(hh, 12, DATEADD(d,DATEDIFF(d,0, #date),0))
END
GO
CREATE FUNCTION [dbo].[get_today_start] (#today datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
return dateadd(day, 0, datediff(d,0,#today))
END
GO
CREATE FUNCTION [dbo].[get_tomorrow_noon](#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
RETURN DATEADD(hh, 12, DATEADD(d,DATEDIFF(d,-1, #date),0))
END
GO
CREATE FUNCTION [dbo].[get_week_end] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
return dateadd(yyyy, datepart(yyyy,
dateadd(weekday,7-datepart(weekday, #date),#date))-1900, 0)
+ dateadd(ms, -3,
dateadd(dy, datepart(dy,
dateadd(weekday,7-datepart(weekday, #date),#date)),0) )
END
GO
CREATE FUNCTION [dbo].[get_week_start] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
return dateadd(yyyy, datepart(yyyy,
dateadd(weekday,1-datepart(weekday, #date),#date))-1900, 0)
+ dateadd(dy, datepart(dy,
dateadd(weekday,1-datepart(weekday, #date),#date))-1,0)
END
GO
CREATE FUNCTION [dbo].[get_weekday_end] (#weekday tinyint,
#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
return dateadd(yyyy, datepart(yyyy,
dateadd(weekday,#weekday-
datepart(weekday, #date),#date))-1900, 0)
+ dateadd(ms, -3,
dateadd(dy, datepart(dy,
dateadd(weekday,#weekday-datepart(weekday, #date),
#date)),0) )
END
GO
CREATE FUNCTION [dbo].[get_weekday_start] (#weekday tinyint,
#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
return dateadd(yyyy, datepart(yyyy,
dateadd(weekday,#weekday-
datepart(weekday, #date),#date))-1900, 0)
+ dateadd(dy, datepart(dy,
dateadd(weekday,#weekday-datepart(weekday, #date),
#date))-1,0)
END
GO
CREATE FUNCTION [dbo].[get_year_end] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
RETURN DATEADD(year, DATEDIFF(year, 0, GetDate())+1, 0)-1
END
GO
CREATE FUNCTION [dbo].[get_year_start] (#date datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
RETURN DATEADD(year,DATEDIFF(year,0, #date),0)
END
GO
CREATE FUNCTION [dbo].[get_yesterday_end] (#today datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
return dateadd(ms, -3, datediff(d,0,#today))
END
GO
CREATE FUNCTION [dbo].[get_yesterday_start] (#today datetime)
RETURNS datetime
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS BEGIN
RETURN dateadd(day, -1, datediff(d,0,#today))
END
GO
These were really helpful for me because I used this in reporting services for date parameters. You could simply create a dataset referencing this table function and then use these in the parameters for any datetime within RS.
You could execute this entire table-valued function like so:
SELECT * FROM [MyDB].[dbo].[udfCommonDates] (GetDate())
The result is like so
For Reporting Services Folks
Now I mentioned earlier that I use these for reporting services.
Now the RS folks might be thinking but how does this help me as I need a dataset and a dataset can only be based on a Stored Procedure or a direct table. No problem create the following stored procedure:
CREATE PROCEDURE [dbo].[uspCommonDates] AS
begin
set datefirst 1
declare #date datetime
set #date = getdate()
select * from dbo.udfCommonDates(#date)
end
Now you've got a stored procedure to use as a dataset...Now in reporting services add a new dataset:
Now go to the report parameters section of the report:
Now pick that dataset dsFunctions (or whatever you called it) and then pick any of the value fields from the scalar functions such as:
Now when you run the report it uses the scalars:
Also now in your "Subscription" you will see a "Use Default" checkbox next to the
parameter for the date. If you check this checkbox it will automatically use the default
value provided by this custom function. It is very very flexible and a very nice solution in reporting services. Here is a screen print of that:
On the report parameter configuration (on development time, not on the subscription creation), add a default value for the parameter. If you do, you will have a check box called "use default value" when creating the subscription
My favorite trick to handle this situation is to create an Integer parameter called StartWeek. Prompt of "The week starting:" Available values like:
Value Label
-4 =dateadd("d",0-weekday(today)+2+(-4*7),today).ToString("m")
-3 =dateadd("d",0-weekday(today)+2+(-3*7),today).ToString("m")
-2 =dateadd("d",0-weekday(today)+2+(-2*7),today).ToString("m")
-1 Previous Week
0 Current Week
1 Last Month
2 This Month
Default value of -1.
Then in your query:
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
DECLARE #CurrentDate DATETIME
SET #CurrentDate = GETDATE()
--SET #CurrentDate = 'October 31, 2011' -- for debugging
IF ( #StartWeek > 0 )
BEGIN
SET #StartDate = DATEADD(mm, DATEDIFF(mm, 0, #CurrentDate), 0)
SET #StartDate = DATEADD(mm, 2 - #StartWeek, #StartDate)
SET #EndDate = DATEADD(s, -1, DATEADD(mm, 1, #StartDate))
END
ELSE
BEGIN
SET #StartDate = DATEADD(wk,
DATEDIFF(wk, 0, DATEADD(d, -1, #CurrentDate))
+ #StartWeek, 0)
SET #EndDate = DATEADD(s, -1, DATEADD(day, 7, #StartDate))
END
Select
*
FROM
MyTable
WHERE
BeginDate <= #EndDate
AND FinishDate >= #StartDate
BeginDate
=DateAdd("d", -12, Today())
EndDate
=DateAdd("d", -6, Today())
So for the upcoming Friday 2/10. This would give you a date range of 1/29 - 2/4.

T-SQL IF Block Not Executing Though Conditions Are Met

I've got the following SQL statement that I am working on. I've trimmed it down to the parts necessary to illustrate the problem.
DECLARE #mwareId as int = 9647,
#startDate as datetime = '2011-07-20',
#endDate as datetime = '2011-07-20'
IF OBJECT_ID('tempdb..#tmpInvoiceList', 'U') IS NOT NULL DROP TABLE #tmpInvoiceList
-- Get base invoice list for customer
SELECT invoiceId
,invoiceNumber
,customerId
,customerName
,customerCode
,createDate
,lastModifiedDate
,invoiceDate
,totalInvoiceAmount
,statusId
,isPaid
INTO #tmpInvoiceList
FROM Invoice.Invoice
-- Apply date range if applicable
IF ( #startDate != NULL AND #endDate != NULL )
BEGIN
DELETE FROM #tmpInvoiceList
WHERE invoiceDate NOT BETWEEN #startDate AND #endDate
END
SELECT * FROM #tmpInvoiceList
I have the #startDate and #endDate variables set to date values. The problem is that the if block that applies the date range to the temp table is not executing, though neither of the two variables are null, and I can't find a reason for this.
As far as I'm aware, TSQL doesn't support the != operator for null checks. Try this:
IF ( #startDate IS NOT NULL AND #endDate IS NOT NULL )
IS [NOT] NULL is the right way to compare value with NULL. All of (NULL != NULL) , (1!= NULL), (NULL =NULL) evaluate as NULL(false)
You have to use IS NOT NULL instead of != NULL
IF ( #startDate IS NOT NULL AND #endDate IS NOT NULL )
...