473,748 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with using BETWEEN for date range...

Hi all -

This problem has been driving me crazy, and I'm hoping the answer is
something stupid I am neglecting to see....

The procedure posted below is part of an Access/SQL database I have
developed. Basically, the user would input a beginning and ending date,
and the query goes and pulls records that meet the following criteria:

1. TradeDate is between beginning date and ending date
2. TradeTime is between beginning date and ending date
3. Trade's Match ID is equal to match IDs returned by the second select
statement - this is part of a ticket processing system, and tickets are
grouped using their match id. So, if one ticket has been updated and
now meets criteria #1 or #2 above, this is supposed to also return any
of the other tickets with the same match ID - so if one ticket in a
group changes, our acct. dept can look at the whole group on their
reports.

Anyway, the query below seems to work, but I am not happy with it. The
problem was I was using the BETWEEN function, and not converting all
the dates to varchar. This worked fine, unless the beginning date and
ending date were the same. For example, if I had a ticket with a
tradedate of 5/3/06 and I ran a beginning date of 5/3/06 and an ending
date of 5/3/06, the ticket should be returned. However, with the
BETWEEN statement, it would return no rows.

I changed the BETWEEN statements to statements like:

tradedate >= beginning date and tradedate <= ending date

but this also returned no rows.

It was only upon converting all the dates to varchar and using the <=
and >= operators that I started getting the results I need.

Can someone tell me why the heck BETWEEN wouldn't work? Tradedate and
Tradetime are both datetime values, and I was bringing in the beginning
and ending date variables in datetime form...is there a problem using
BETWEEN when the first and second variables used are the same?

Any light you can shed on this would be great, because having all these
convert statements and such makes me nervous...I'd rather get between
to work, but I have not been able to in my testing...

Thanks! -Jim

CREATE PROCEDURE dbo.spAcctExpor t(@begindate datetime,
@enddate datetime)
AS SELECT TOP 100 PERCENT dbo.tblTradeAcc ount.Accounting Code AS
TradeAccount, dbo.tblOrders.T icketNum, dbo.tblOrders.T radeDate,
dbo.tblOrders.S ettleDate, NULL AS
ProductionMonth , dbo.tblOrders.R epID, dbo.tblOrders.A cctNum,
dbo.tblAccounts .Shortname, dbo.tblOrders.Q uantity,
dbo.TBLCUSIP.Fa ctor, dbo.tblOrders.B uySell,
dbo.tblOrders.C USIP, dbo.TBLCUSIP.Is suer, dbo.TBLCUSIP.Po olNum,
dbo.TBLCUSIP.Co upon,
dbo.tblOrders.F ixAdj, dbo.tblOrders.P rice,
dbo.tblOrders.R epSC, '=(H:H*I:I*Q:Q)/100' AS Markup, 'PTMSA' AS
ProdType, dbo.tblOrders.D eskSC,
dbo.tblOrders.R epCarry, '=(H:H*I:I*T:T)/100' AS
DeskMarkup, dbo.tblOrders.M atchID,

'=IF(K:K="B",(( I:I*H:H*P:P)/100)*-1,(I:I*H:H*P:P)/100)' AS
TotalPrincipal, dbo.tblOrders.C ancelCorrect,
dbo.tblOrders.O riginalTrade,
dbo.tblOrders.T radeTime, dbo.tblOrders.R ep2ID,
dbo.tblOrders.R ep2SC
FROM dbo.tblOrders INNER JOIN
dbo.TBLCUSIP ON dbo.tblOrders.C USIP =
dbo.TBLCUSIP.CU SIP INNER JOIN
dbo.tblAccounts ON dbo.tblOrders.A cctNum =
dbo.tblAccounts .AcctNum INNER JOIN
dbo.tblTradeAcc ount ON dbo.tblOrders.T radeAccount
= dbo.tblTradeAcc ount.TradeAccou nt
WHERE ((

(dbo.tblOrders. MatchID IS NOT NULL) AND (dbo.tblOrders. MatchID IN
(SELECT MatchID FROM dbo.tblOrders WHERE (

CONVERT(VARCHAR (10),dbo.tblOrd ers.TradeDate,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) AND
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADEDATE,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))

OR (

CONVERT(VARCHAR (10),dbo.tblOrd ers.TradeTime,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) AND
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADETIME,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))) ))

OR ((

CONVERT(VARCHAR (10),dbo.tblOrd ers.TradeDate,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) and
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADEDATE,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))

OR (

CONVERT(VARCHAR (10),DBO.TBLORD ERS.TradeTime,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) AND
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADETIME,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))) )

ORDER BY dbo.tblOrders.C ancelCorrect,
dbo.tblTradeAcc ount.Accounting Code, dbo.tblOrders.M atchID,
dbo.tblOrders.B uySell, dbo.tblOrders.T icketNum
GO

May 3 '06 #1
13 10706
In SQL Server, there is not DATE data type or TIME data type -- but
there is a single DATETIME. Quit doing all that converting and work
with temporal expressions instead of COBOL-style strings. Think in
abstract terms, not how it is displayed on a piece of paper or a
screen.

WHERE trade_time BETWEEN start_time AND end_time

will work fine, if you bother to add constraints to start_time (i.e
00:00:00) and end_time (23:59:59.9999) columns. Another trick is to
allow end_time to be NULL when an event is still in progress and then
use COALESCE (end_time, CURRENT_TIMESTA MP)

If you look up Rick Snodgrass at University of Arizona, you can
download his out-of-print book on temporal SQL queries.

May 3 '06 #2
OK - my post mentioned I originally used

WHERE tradedate BETWEEN begindate AND enddate

Begindate and enddate are not columns - they are parameters the user
supplies in the format mm/dd/yyyy.

My whole post was explaining that I would *prefer* to use the BETWEEN
AND statement - the converting was not my choice, but it is the only
way this query works when the user specifices the same date as
begindate and enddate.

So once again - can someone explain why this query returns no records
when begindate and enddate are specified as 5/3/2006 and there is
clearly trade data with that tradetime?

May 3 '06 #3
My assumption is that the tradedate is a datetime datatype that
includes a time, while the begin and end dates are just dates. The
comparison is will be done on datetimes, which include both date and
time.
WHERE tradedate BETWEEN begindate AND enddate
Consider what this can look like when we substitute actual values.

WHERE
'2006-05-03 17:12:51.420' BETWEEN
'2006-05-03 00:00:00.000' AND
'2006-05-03 00:00:00.000'

The time that is part of tradedate is putting it outside of the
"range" of the BETWEEN; in this case of course the BETWEEN has no
range, being two identical points in time. To match it needs a 24
hour range, but that is not what it has.

To use BETWEEN you would need toto reduce tradedate to a simple date
with no time for the test.

Roy Harvey
Beacon Falls, CT

On 3 May 2006 13:40:16 -0700, "Jim Armstrong"
<ar*********@ho tmail.com> wrote:
OK - my post mentioned I originally used

WHERE tradedate BETWEEN begindate AND enddate

Begindate and enddate are not columns - they are parameters the user
supplies in the format mm/dd/yyyy.

My whole post was explaining that I would *prefer* to use the BETWEEN
AND statement - the converting was not my choice, but it is the only
way this query works when the user specifices the same date as
begindate and enddate.

So once again - can someone explain why this query returns no records
when begindate and enddate are specified as 5/3/2006 and there is
clearly trade data with that tradetime?

May 3 '06 #4
Jim Armstrong (ar*********@ho tmail.com) writes:
CONVERT(VARCHAR (10),dbo.tblOrd ers.TradeDate,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) AND
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADEDATE,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))
But this does not make any sense. When I run

select convert(varchar (10), getdate(), 101)

I get

05/03/2006

So if the user enters 2006-05-03, you will also give him hits from
2005???

If you feel compelled to use string format, use format 112 which is
YYYYMMDD, which is possible to compare, and which also is unambiguosly
convertible back to date.

But it would make more sense to simple say:

O.TradeDate BETWEEN @begindate AND @enddate

Provided that is, that TradeDate always have a timeportion of midnight.
And the same provision applies to @begindate and @endate, but I got
the impression that the user enters date only.

If TradeDate also includes hours and seconds, you need to write:

O.TradeDate >= @begindate AND
O.TradeDate < dateadd(DAY, 1, @enddate)

There is one more important thing to observer here: you should avoid
putting TradeDate in an expression. This is because if there is an
index on TradeDate, that index cannot be used if you put TradeDate in
an expression, and performance will suffer.
CONVERT(VARCHAR (10),dbo.tblOrd ers.TradeTime,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) AND
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADETIME,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))) ))
The same applies here, although I'm not really clear what is in TradeTime.
Is TradeDate 2006-05-03 00:00:00 and TradeTime is 2006-05-03 12:23:23?

In such case, I'm not sure why you need to check both.
CONVERT(VARCHAR (10),dbo.tblOrd ers.TradeDate,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) and
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADEDATE,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))

OR (

CONVERT(VARCHAR (10),DBO.TBLORD ERS.TradeTime,1 01) >=
CONVERT(VARCHAR (10), @begindate,101) AND
CONVERT(VARCHAR (10),DBO.TBLORD ERS.TRADETIME,1 01) <=
CONVERT(VARCHAR (10), @enddate,101))) )


And then you have it once more?

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
May 3 '06 #5
>> So once again - can someone explain why this query returns no records [sic] when begindate and enddate are specified as 5/3/2006 and there is clearly trade data with that tradetime? <<

Once again, because there is a DATETIME column which has a time on it.
If you do not give the time, it defautls to 00:00:00.000 Hrs. This is
a single point in time. What you wanted to use was

WHERE tradedate BETWEEN '2006-05-03 00:00:00.000' AND '2006-05-03
23:59:59.99'

You might also want to learn ISO standards and use 'yyyy--mm-dd' for
date values.

And do not forget to add constraints to temporal columns in your base
tables.

May 4 '06 #6
Yes but hang on a minute, what if you don't want a time, holding the time
component is misleading that indicates the data value may contain a time
between 00:00:00 and 23:59:59, being 00:00:00 means the trade was done at
midnight which may well not be true, consider settment date where the trade
needs to settle on a particular day, not by midnight but sometime on that
day.

In SQL Server because we don't have a DATE data type we need to store dates
as an integer in the form yyyymmdd which is unfortunate but the reality.
You might also want to learn ISO standards and use 'yyyy--mm-dd' for
date values.


Rich coming from the guy who doesn't use the standard format himself.

2006-05-03 00:00:00.000 should be written 2006-05-03T00:00:00.000

OR

20060503 if you are only specifying the date.

--
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jc*******@eart hlink.net> wrote in message
news:11******** *************@i 40g2000cwc.goog legroups.com...
So once again - can someone explain why this query returns no records
[sic] when begindate and enddate are specified as 5/3/2006 and there is
clearly trade data with that tradetime? <<


Once again, because there is a DATETIME column which has a time on it.
If you do not give the time, it defautls to 00:00:00.000 Hrs. This is
a single point in time. What you wanted to use was

WHERE tradedate BETWEEN '2006-05-03 00:00:00.000' AND '2006-05-03
23:59:59.99'

You might also want to learn ISO standards and use 'yyyy--mm-dd' for
date values.

And do not forget to add constraints to temporal columns in your base
tables.

May 4 '06 #7
Tony Rogerson (to**********@s qlserverfaq.com ) writes:
Yes but hang on a minute, what if you don't want a time, holding the
time component is misleading that indicates the data value may contain a
time between 00:00:00 and 23:59:59, being 00:00:00 means the trade was
done at midnight which may well not be true, consider settment date
where the trade needs to settle on a particular day, not by midnight but
sometime on that day.

In SQL Server because we don't have a DATE data type we need to store
dates as an integer in the form yyyymmdd which is unfortunate but the
reality.


Only if you like to throw out babies and bathtubs simultaneously.

All our settledate columns are datetime, or more precisely aba_date,
which is a datetime with a rule bound to that screams blue murder if
you try to use anything else than 00:00:00.000 for the time porttion.

And, no, our customers do not settle at midnight.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
May 4 '06 #8
> All our settledate columns are datetime, or more precisely aba_date,
which is a datetime with a rule bound to that screams blue murder if
you try to use anything else than 00:00:00.000 for the time porttion.

And, no, our customers do not settle at midnight.
Presumeably you also have a computed column that strips away the time
component so only the date gets passed back to the client?

To quote celko, using datetime to hold a pure date is really a kludge ;),
seriously though, even though you have a check constraint to prevent times
over than midnight, it shouldn't have a time at all and any query result
should not contain a time component, it ensinuates that settment date is not
a date but actually a date with a time, so to the application developer or
third party vendor accessing your webservice etc... it might well appear
that trades should be settled by midnight.

All the trading systems I've worked with ALL use the integer data type to
hold pure dates.

--
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Erland Sommarskog" <es****@sommars kog.se> wrote in message
news:Xn******** **************@ 127.0.0.1... Tony Rogerson (to**********@s qlserverfaq.com ) writes:
Yes but hang on a minute, what if you don't want a time, holding the
time component is misleading that indicates the data value may contain a
time between 00:00:00 and 23:59:59, being 00:00:00 means the trade was
done at midnight which may well not be true, consider settment date
where the trade needs to settle on a particular day, not by midnight but
sometime on that day.

In SQL Server because we don't have a DATE data type we need to store
dates as an integer in the form yyyymmdd which is unfortunate but the
reality.


Only if you like to throw out babies and bathtubs simultaneously.

All our settledate columns are datetime, or more precisely aba_date,
which is a datetime with a rule bound to that screams blue murder if
you try to use anything else than 00:00:00.000 for the time porttion.

And, no, our customers do not settle at midnight.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx

May 5 '06 #9
Tony Rogerson (to**********@s qlserverfaq.com ) writes:
Presumeably you also have a computed column that strips away the time
component so only the date gets passed back to the client?
Computed column? Hey, this system started its life in SQL Server 4.x. And
you cannot accuse for being too quick to leave SQL 6.5. I think we have
two computed columns in the system.

Yes, the time portion is a bit of noice in Query Analyzer. For the client,
it is a non-issue.
All the trading systems I've worked with ALL use the integer data type to
hold pure dates.


One of our competitors seems to go by char(8). (They're not using SQL
Server. Their system runs on AS 400, so I guess it's DB2.) We have taken
over several of their customers and converted their data to our system.
I've seen some completely hilarous dates there.

Using integer or char(8) for dates is in my opinion an even worse solution,
as you run the risk of getting dates like 20060230 and that in the system.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
May 5 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
14895
by: BlackFireNova | last post by:
I need to write a report in which one part shows a count of how many total records fall within the working days (Monday - Friday) inside of a (prompted) given date range, in a particular geographical region. I have written a query which prompts the user for the start and end dates. It also filters for entries which pertain to the particular geographical region. I'm not sure where to go from here.
4
2493
by: Stewart Allen | last post by:
I'm trying to filter a table that has 2 date fields, the first date will always have a value but the second will only occasionally has a value. Each date field also has a corresponding text field to record the record's status. Sample data: *tblTest* Model Parts CDate CStatus RDate RStatus 616 $359.79 03-Nov-03 C
12
6390
by: Steve Elliott | last post by:
I have a query set up to gather together data between two specified dates. Shown in the query column as: Between #24/09/2004# And #01/10/2004# Is it possible to enter several different date ranges, ie between 24/09/2004 and 01/10/2004 together with 05/10/2004 and 07/10/2004 ? If I enter the "Between" criteria on different lines it returns no data.
3
1031
by: jhcorey | last post by:
I have a stored procedure that takes 14 parameters, including two for start date and end date. The procedure then creates a sql string and does an 'exec sql'. The stored procedure always works correctly when I run it stand alone. When I run it in my app, I sometimes get duplicate records, and sometimes get no records. This is based on date range. I set the range to 8/1/04 to 9/1/04, and I get a double set of records in the dataset....
6
3234
by: alexanderpope11 | last post by:
Hello, how do I write this SQL: I would like to check the Main table for invalid rows. An invalid row is: any row where the Start_date to stop_date range overlaps an invalid date in the Code table. For example, Row#2 is invalid because the Start_date-Stop_Date range overlaps 2 days in the code table where the code AA was not valid (12/30/2000 - 12/31/2000) Main Table
8
2454
by: sara | last post by:
I have a report that runs fine with data. If there is no data, I have its NO Data event sending a MsgBox and cancelling the report. Then it seems I still get the 2501 message on the Open Report command, even though I have the code to trap Err 2501 (from many postings - all looked the same to me) on the button the user pressed to get the report. I never see the code going to my error handling on the button. If I debug, I am in an...
3
6310
by: Ray | last post by:
Hi, I'm working on something with mysql and excel. I'm using python and win32com. All major function works, But I have two problems: 1. the output need to do "auto fit" to make it readable. I tried to call "xlApp.Columns.AutoFit=1" the whole program will crash, but without xlApp.Columns.AutoFit=1, everything just fine.
3
1278
by: girl | last post by:
i have this problem m using dataset dataadapter and dataset i would like to select a date range using a datetimepicker or monthcalendar. the data in my database for date is 05/01/2007 where 05 is the month and 01 is the date. sqladapter.SelectCommand = New OdbcCommand("SELECT * from " & table & "where date between @from_date and @to_date", conn)
0
1346
by: GiftX | last post by:
VB 6.0 And Spreadsheet - Printing problem Good morning West. After much research, I found this code. It scans the spreadsheet and returns up to the last used cell. xlWksht.Cells.Find(What:="*", After:=, SearchDirection:=xlPrevious).Select Note: The above code returned all the data in the used cells. Print Problem#1: Based on the code above, I execute this code: Selection.PrintOut But instead of printing the data returned with the...
9
2779
by: QCLee | last post by:
Sir can you help me to transfer my Access Query to MS excel? i have a command button on the form to export the parameter query named "HVACWindwardQuery" to excel spreadsheet and i got the codes from searching on the internet and books but the problem is when i run the command button "Export" it just only open the Blank Spreadsheet, no data at all that it came from my query named "HVACWindwardQuery" and there's an error on it...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3319
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.