Question

DateAdd logic in SQL

Asked by: BobRosas

I'm using Business Intelligence Development Studio in Visual Studio 2005 environment.  
When I preview a report with the parameter dates of 7/3/08 to 7/3/08 I get no results.
When I use dates of 7/3/08 to 7/4/08 I get 5 records dated 7/3/08.  Because of help from EE I understand why it's happening but need help with the code.  I've attached what it should be logically but I get the error...
Cannot compare data of types System.DateTime and System.String

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-09-17 at 09:44:49ID23739376
Tags

SQL

,

Microsoft Visual Studio 2005

Topics

SQL Server 2005

,

Visual Studio

Participating Experts
2
Points
125
Comments
18

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Business Intelligence option not showing in Visual studio 2…
    I have installed visual studio 2003 and ms sql server 2000 personal edition, but when I open a new report the Business Intelligence Projects Option does not appear.
  2. In Visual Studio, Business Intelligence does not appear
    We have SQL Server 2000 loaded on one of our servers, yet when I start a New Project from within Visual Studio, Business Intelligence Projects does not appear as one of my Project Types (Visual Basic, Visual C#, Visual J#, Visual C++, Setup and Deployment Other and Visual Stu...
  3. Bussiness Intelligence Project in Visual Studio 2008
    Is there a way to create a Business Intelligence Project in Visual Studio 2008 without using SQL Server 2008?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: simonetPosted on 2008-09-17 at 09:51:48ID: 22500873

That's because the Datetime fields contains a decimal part that holds the hour/minute/second part of the date.

When comparing dates, if you're interested only in the date part (regardless of the time part), you can have a where clause like this:

WHERE (cast(cast(SomeDateField as int) as datetime) = '3 JUL 2008')

if you want to compare intervals of time:

WHERE (cast(cast(SomeDateField as int) as datetime) between '3 JUL 2008' and '07 JUL 2008')

This will yield correct results.

In short, what you need to do when comparing dates, is force SQL Server to ignore the time component of the datetime field, so that the comparisions are accurate.

Alex




 

by: BrandonGalderisiPosted on 2008-09-17 at 09:58:49ID: 22500966

Your field that you are comparing it to needs to have the time portion stripped out.  To strip out the time portion and allow for date only comparison....

where convert(datetime,convert(char(8),YourDateField,112),112) = @YourDateParameter

 

by: BobRosasPosted on 2008-09-17 at 10:18:46ID: 22501196

Thank you both for your quick responses.  I tried making changes to my code using Brandon's suggestion because it made more sense with my existing code.  But I admit I'm new to SQL and I've gotten EE help on the code I have so far so I'm unsure of my changes.  It complies and runs in data view but when I try to preview the report I get the same error.  Is what I'm trying to do not possible with a filter?  Do I have to use a parameter?  
Thanks again!

WITH original_data AS (
SELECT g.Timetag
     , u.Name UName
     , g.AName
FROM  dbo.Users u
INNER JOIN dbo.GPSData g
  ON u.UserID = g.UserID
WHERE u.Name = @Name
  and g.Timetag BETWEEN DATEADD(m, - 3, CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112), 112)) 
  AND CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112), 112) 
  AND g.Timetag BETWEEN DATEADD(m, - 3, GETDATE()) AND 
CONVERT(DATETIME, CONVERT(VARCHAR(8), 
CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(), 112), 112), 112), 112) 
AND g.AName IS NOT NULL 
GROUP BY u.Name, g.AName, g.Timetag
) -- with original_data 
, row_numbered_data as ( 
  SELECT Timetag  
       , uName
       , AName
       , ROW_NUMBER() OVER (PARTITION BY uName ORDER BY TimeTag) r 
  FROM original_data 
) -- with row_numbered_data
SELECT c.TimeTag, c.uName, c.AName
  FROM row_numbered_data c
  LEFT JOIN row_numbered_data p
    ON c.uName = p.uName
   AND c.r = p.r + 1
  WHERE p.AName is null 
     OR p.AName <> c.AName

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

Select allOpen in new window

 

by: BrandonGalderisiPosted on 2008-09-17 at 10:20:52ID: 22501216

How about your post code before you made these changes, and we can help plug them in.  I see what appears to be some extra converts and I want to make sure it's right before this change

 

by: BobRosasPosted on 2008-09-17 at 11:08:13ID: 22501774

Gladly.  
I actually gave you 2 snippets.  One is because I was using GetDate and EE advised me that GetDate uses time, so change to convert.  
The 2nd snippet includes convert changes I added which may explain why it doesn't look quite right.  Since it gave the same final result I thought it was working but I admit it's hard to read.
Your help is greatly appreciated.

THIS IS BEFORE CONVERT 
WITH original_data AS (
SELECT g.Timetag
     , u.Name UName
     , g.AName
FROM  dbo.Users u
INNER JOIN dbo.GPSData g
  ON u.UserID = g.UserID
WHERE u.Name = @Name
  and g.Timetag BETWEEN DATEADD(m, - 3, GETDATE()) AND GETDATE() 
  AND g.Timetag BETWEEN DATEADD(m, - 3, GETDATE()) AND GETDATE() 
  AND g.AName IS NOT NULL 
GROUP BY u.Name, g.AName, g.Timetag
) -- with original_data 
, row_numbered_data as ( 
  SELECT Timetag  
       , uName
       , AName
       , ROW_NUMBER() OVER (PARTITION BY uName ORDER BY TimeTag) r 
  FROM original_data 
) -- with row_numbered_data
SELECT c.TimeTag, c.uName, c.AName
  FROM row_numbered_data c
  LEFT JOIN row_numbered_data p
    ON c.uName = p.uName
   AND c.r = p.r + 1
  WHERE p.AName is null 
     OR p.AName <> c.AName
 
 
THIS IS AFTER CONVERT
WITH original_data AS (
SELECT g.Timetag
     , u.Name UName
     , g.AName
FROM  dbo.Users u
INNER JOIN dbo.GPSData g
  ON u.UserID = g.UserID
WHERE u.Name = @Name
  and g.Timetag BETWEEN DATEADD(m, - 3, CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120)) 
  AND CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120) 
  AND g.Timetag BETWEEN DATEADD(m, - 3, GETDATE()) AND 
CONVERT(DATETIME, CONVERT(VARCHAR(10), 
CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120), 120), 120) 
  AND g.AName IS NOT NULL 
GROUP BY u.Name, g.AName, g.Timetag
) -- with original_data 
, row_numbered_data as ( 
  SELECT Timetag  
       , uName
       , AName
       , ROW_NUMBER() OVER (PARTITION BY uName ORDER BY TimeTag) r 
  FROM original_data 
) -- with row_numbered_data
SELECT c.TimeTag, c.uName, c.AName
  FROM row_numbered_data c
  LEFT JOIN row_numbered_data p
    ON c.uName = p.uName
   AND c.r = p.r + 1
  WHERE p.AName is null 
     OR p.AName <> c.AName

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:

Select allOpen in new window

 

by: BobRosasPosted on 2008-09-18 at 13:29:05ID: 22515073

I didn't mean to scare you away.  I thought your code was helpful.  I took out the GETDATE in my code and added your code and I get the results I want...Thanks!  It made sense that insteasd of getting the last 3 months and the narrowing it down from there that I should just get exactly what I need.  That way it's faster...well so I thought.  With the GETDATE it takes about 30 seconds to run which I thought was kind of long.  Without that it takes almost 3 minutes.  Shouldn't it take less time?  Can you take another look at my newly posted code.  I'd really appreciate it.
Thanks!

WITH original_data AS (
SELECT g.Timetag
     , u.Name UName
     , g.AName
FROM  dbo.Users u
INNER JOIN dbo.GPSData g
  ON u.UserID = g.UserID
WHERE u.Name = @Name
  and convert(datetime,convert(char(8), g.Timetag,112),112)= @FromDate
  and convert(datetime,convert(char(8), g.Timetag,112),112)= @ToDate
  AND g.AName IS NOT NULL 
GROUP BY u.Name, g.AName, g.Timetag
) -- with original_data 
, row_numbered_data as ( 
  SELECT Timetag  
       , uName
       , AName
       , ROW_NUMBER() OVER (PARTITION BY uName ORDER BY TimeTag) r 
  FROM original_data 
) -- with row_numbered_data
SELECT c.TimeTag, c.uName, c.AName
  FROM row_numbered_data c
  LEFT JOIN row_numbered_data p
    ON c.uName = p.uName
   AND c.r = p.r + 1
  WHERE p.AName is null 
     OR p.AName <> c.AName

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

 

by: BrandonGalderisiPosted on 2008-09-18 at 13:57:11ID: 22515389

Don't worry, you didn't scare me away as much as this "comment added" email accidentally got deleted along with the hundreds of others I receive daily.

To clarify, it's working, but not fast enough?

 

by: BrandonGalderisiPosted on 2008-09-18 at 14:02:43ID: 22515449

To understand your query, because I think you are making it more complicated than necessary

So you are attempting to show the current and previous record, on a single line, from the GPSdata table, as it relates to a user, for a given time period?

<apology>run on sentence</apology>

 

by: BrandonGalderisiPosted on 2008-09-18 at 14:05:10ID: 22515479

Do you have an index on dbo.users.name?

 

by: BrandonGalderisiPosted on 2008-09-18 at 14:07:58ID: 22515512

Or are you trying to show all changes in location for a given user, since each timetag may be in the same location, you want to find what time the change in position occurred and list the timetag, the username and the aName?

 

by: BrandonGalderisiPosted on 2008-09-18 at 14:14:26ID: 22515563

"IF" I interpreted our query right and "IF" I understand your data model, this may work correctly, and better:


Try experimenting with y1.* and y2.* below.


with YourData as (select u.userid,g.TimeTag,u.[Name] UName,g.AName,row_number() over(partition by u.[Name] order by g.TimeTag) r
from dbo.users u
join dbo.gpsdata g
on u.userid = g.userid
where u.[name] = @name
  and convert(datetime,convert(char(8), g.Timetag,112),112) >= @FromDate
  and convert(datetime,convert(char(8), g.Timetag,112),112) <  @ToDate
  and g.AName is not null)
  
select y1.* from YourData y1
 left outer join YourData y2
   on y1.userid = y2.userid
   and y1.r = y2.r-1
where case when y1.aName = y2.aName then 0 else 1 end = 1

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: BobRosasPosted on 2008-09-18 at 14:18:00ID: 22515593

I'm glad you are back.  I'll try to answer all your questions.
Ques 1.  You are correct.  I think it should be faster but that is based on the fact that with GETDATE is 32 seconds and without is over 3 minutes.  I thought my just picking specific data it should be faster.  Therefore I figure it's something I did in my code.
2.  It may be easier if I give you a link to my previously posted question.
  http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SQL-Server-2005/Q_23735903.html
3.  Yes there is an index on dbo.users.name
4.  I think the link should clarify this as well.
5. I will try your posted code and let you know.  Thank you so much

 

by: BobRosasPosted on 2008-09-18 at 14:44:18ID: 22515830

I tried the new code and it does compile and run but it does not return any results.  If I try to run it in Preview I get the error...
'System out of memory error was thrown'

Was the link I gave you of any help?  If not I'd be glad to try and explain it here.  I just appreciate your help.
Thanks

 

by: BrandonGalderisiPosted on 2008-09-19 at 07:49:39ID: 22521701

Change the select portion of the query to this to test it.

You should get
record1       > record2
record2       > record3
record3       > record4

two records per line.  

select top 100 y1.*,y2.* from YourData y1
 left outer join YourData y2
   on y1.userid = y2.userid
   and y1.r = y2.r-1
                                              
1:
2:
3:
4:

Select allOpen in new window

 

by: BobRosasPosted on 2008-09-19 at 09:26:58ID: 22522892

Thank you so much for your continued help.  I tried your suggestion but it still does not display any results.  
However, the code I've attached is giving me the data I want and it's fast so I will use it.  Even tho I don't know why I need the following portion of the code.  It works without it but really really slow.  It appears I'm grabbing 3 months of data and then selecting one date from that data.  Shouldn't it be faster to just select the one date?
Oh well.  Please advise if you know why but I will go ahead and award points since it works.
Thanks again.

  and g.Timetag BETWEEN DATEADD(m, - 3, CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120))
  AND CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120)
  AND g.Timetag BETWEEN DATEADD(m, - 3, GETDATE()) AND
CONVERT(DATETIME, CONVERT(VARCHAR(10),
CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120), 120), 120)

WITH original_data AS (
SELECT g.Timetag
     , u.Name UName
     , g.AName
FROM  dbo.Users u
INNER JOIN dbo.GPSData g
  ON u.UserID = g.UserID
WHERE u.Name = @Name
  and g.Timetag BETWEEN DATEADD(m, - 3, CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120)) 
  AND CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120) 
  AND g.Timetag BETWEEN DATEADD(m, - 3, GETDATE()) AND 
CONVERT(DATETIME, CONVERT(VARCHAR(10), 
CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120), 120), 120), 120) 
  and convert(datetime,convert(char(8), g.Timetag,112),112)>= @FromDate
  and convert(datetime,convert(char(8), g.Timetag,112),112)<= @ToDate
  AND g.AName IS NOT NULL 
GROUP BY u.Name, g.AName, g.Timetag
) -- with original_data 
, row_numbered_data as ( 
  SELECT Timetag  
       , uName
       , AName
       , ROW_NUMBER() OVER (PARTITION BY uName ORDER BY TimeTag) r 
  FROM original_data 
) -- with row_numbered_data
SELECT c.TimeTag, c.uName, c.AName
  FROM row_numbered_data c
  LEFT JOIN row_numbered_data p
    ON c.uName = p.uName
   AND c.r = p.r + 1
  WHERE p.AName is null 
     OR p.AName <> c.AName

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:

Select allOpen in new window

 

by: BobRosasPosted on 2008-09-19 at 09:28:32ID: 31497406

Adding this parameter and taking out the filters is what got me wher I need to be.  Thanks

 

by: BrandonGalderisiPosted on 2008-09-19 at 09:36:07ID: 22522963

You are filtering by date in the very first section, which is limiting the amount of data returned and making it faster.

 

by: BobRosasPosted on 2008-09-19 at 10:13:22ID: 22523289

Makes sense.  
Thanks again!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...