[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 277
  • Last Modified:

SQL Query date / datediff

Hey

I would like to have the following only find the machines installed from today (4/4/2014) and forward

Howto?

select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_OPERATING_SYSTEM on SMS_G_System_OPERATING_SYSTEM.ResourceId = SMS_R_System.ResourceId    

WHERE    dateDiff(dd, SMS_G_System_OPERATING_SYSTEM.InstallDate, GetDate()) < 30

Open in new window

0
mikeydk
Asked:
mikeydk
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you may want to read up this article about date/time stuff:
http://www.experts-exchange.com/Database/Miscellaneous/A_1499-DATE-and-TIME-don%27t-be-scared-and-do-it-right-the-first-time.html

hence, syntax like this:
WHERE    dateDiff(dd, SMS_G_System_OPERATING_SYSTEM.InstallDate, GetDate()) < 30
should be banned ...
the correct way would be for example:
WHERE    SMS_G_System_OPERATING_SYSTEM.InstallDate > dateadd(day, 30, GetDate())

now, getdate() contains also a time portion (data type is datetime), so you may want to use the date data type instead: CONVERT(date, GETDATE())
http://technet.microsoft.com/en-us/library/ms188383.aspx

for your query, it would look like this:
WHERE    SMS_G_System_OPERATING_SYSTEM.InstallDate > convert(date, getdate())
0
 
ste5anSenior DeveloperCommented:
You should use table alias names to improve readability. E.g.

SELECT  S.ResourceID ,
        S.ResourceType ,
        S.Name ,
        S.SMSUniqueIdentifier ,
        S.ResourceDomainORWorkgroup ,
        S.Client
FROM    SMS_R_System S
        INNER JOIN SMS_G_System_OPERATING_SYSTEM OS ON OS.ResourceId = S.ResourceId
WHERE   DATEDIFF(DAY,OS.InstallDate, GETDATE()) = 1;

Open in new window


btw, there is no "forward"..
0
 
Scott PletcherSenior DBACommented:
WHERE
    SMS_G_System_OPERATING_SYSTEM.InstallDate >= CONVERT(char(8), GETDATE(), 112)
0
 
SharathData EngineerCommented:
SELECT SMS_R_SYSTEM.ResourceID, 
       SMS_R_SYSTEM.ResourceType, 
       SMS_R_SYSTEM.Name, 
       SMS_R_SYSTEM.SMSUniqueIdentifier, 
       SMS_R_SYSTEM.ResourceDomainORWorkgroup, 
       SMS_R_SYSTEM.Client 
  FROM SMS_R_System 
       INNER JOIN SMS_G_System_OPERATING_SYSTEM 
               ON SMS_G_System_OPERATING_SYSTEM.ResourceId = SMS_R_System.ResourceId 
 WHERE SMS_G_System_OPERATING_SYSTEM.InstallDate >= DATEADD(DD, 0, DATEDIFF(DD, 0, GETDATE())) 

Open in new window

0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now