sql parameters for date and time - sql-server

I'm trying to run a query that returns values based on yesterday's date. In this case how many items were shipped out yesterday. This is my query:
shh.SHIP_DATE = dateadd(dd, -1, getdate())
when I run it it doesn't return anything, but when I plug in a date it gives me values:
shh.SHIP_DATE = '2013-12-09'

Is the SHIP_DATE column a date or a datetime? I'm assuming it's a datetime column, but storing only a date value, so when you use getdate() you are going to get the time value as well. You could easily get it working by using the predicate (shh.SHIP_DATE = cast(dateadd(dd, -1, getdate()) as date))

GETDATE() includes the current time as well. You need to truncate the time portion. There's lost of ways to do that - here's one:
shh.SHIP_DATE = DATEADD(dd, DATEDIFF(dd, 0, getdate())-1, 0)
translated - add one less than the number of days between date "0" and today to date "0"

Related

dynamically changing dates in a temp table

So i have a very specific task. I run some sql statements within which there is a temp table which contains date ranges specific to countries.
e.g.
INSERT INTO #dateRange(durationDesc, contryCode,startDate,endDate)
VALUES ('Weekly - TY','UK','20160919','20160925')
,('Weekly - LY','UK','20150921','20150927')
,('Weekly - LW','UK','20150912','20150918')
So, corresponding week previous year. The other range is month to date.
Whats the best way to do this? I'd prefer one where i only need to enter one date and the rest can be updated.
Any questions, feel free to ask.
You can always get current system datetime by GETDATE(), and then modify it accordingly by DATEADD()
For example:
SELECT DATEADD(YEAR, -1, GETDATE()) -- Result in 1 year prior the current system datetime.
SELECT DATEADD(MONTH, 13, GETDATE()) -- Result in 13 months after the current system datetime.
In your code snippet you seems to be converting the datetime into yyyymmdd string format (Although I highly doubt the necessity), which can be achieve by a CONVERT:
SELECT CONVERT(VARCHAR, DATEADD(YEAR, -1, GETDATE()), 112)
For example if today is 10/26/2016, then it should show result as 1 year prior to today in yyyymmdd format, 20151026

Date filter on column in sql

I have query that filtered by date, for now it take only the last 24h from the moment I execute it, for doing that I'm using the next code:
( DateDiff(HH, vw_public_task.complete_date, getdate()) < 25)
There is a way that my date filter will give query results for the last 24h but not depending on my current hour but according to "day 08:00am" -- "day+1 08:00am" at any time that I execute it?.
For example if I execute my query now I want to see date results from yesterday 08:00am till today 08:00am.
You can calculate yesterday 8am using the formula:
-- Yesterday at 8 am.
SELECT
DATEADD(HOUR, 8, CAST(CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS DATETIME)) AS Yesterday8AM
;
GetDate returns the current date. The innermost date add subtracts one day. Casting this as a date removes the timestamp. Casting this back to a DateTime gives yesterday at midnight. Now we are dealing with a DateTime we can use date add, again, to add 8 hours.
If you are using SQL Server 2012, or above, consider the native function DATETIME2FROMPARTS instead.
Use Date() (How to part DATE and TIME from DATETIME in MySQL).
( DateDiff(HH, vw_public_task.complete_date, Date(getdate())+8 ) < 25)

Get date Minus 1 day but at exacty 4 AM

I have the following sql server WHERE clause:
WHERE (DateCreated >= CONVERT(datetime, GETDATE(), 111) - 1)
This gets the date (where today is 2015-06-09) 2015-06-08. I need to add a time to this as well like 2015-06-08 04:00:00 in 24H format. the time will always be the same bat every time the SQL command is executed, it should only be from yesterday at 4 AM to the current date and time.
how can this be achieved?
Try this:
WHERE DateCreated >= dateadd(d, datediff(d, 1, getdate()), '04:00')
I think you are looking for:
WHERE (DateCreated >= DATEADD(HOUR, 4,
CONVERT(datetime,
DATEADD(DAY, -1, CONVERT(date, GETDATE()) )
)
)
)
Converting directly to DATE will take away the hassle of taking care of the hour part. After that, doing a DATEADD with -1 will take you 1 day ago.
After this step, simply convert it back to datetime to create a timestamp part to your date, which is defaulted to 00:00:00.000.
And in the end, simply add 4 hours to this start date, which will always give you 4:00 AM.

How to get one month ago from today in SQL Server 2008?

I´m writing a query where i get the last month, but with the time in zeros (if today is 2013-05-21 then i want to get 2013-04-21 00:00:00.000).
So I tried:
select (dateadd(month,datediff(month,(0),getdate())-1,(0)));
But I get the first day of the previous month.
Then I tried:
select dateadd(month, -1, GETDATE());
I get the right day, but I also get the current time (2013-04-21 11:41:31.090), and I want the time in zeros.
So how should my query be in order to get something like: 2013-04-21 00:00:00.000
Thanks in advance.
In SQL Server 2008 there is the date data type, which has no time attached. You can thus remove the time portion quite easily simply by converting, then performing the DateAdd.
SELECT DateAdd(month, -1, Convert(date, GetDate()));
This will return a date data type. To force it to be datetime again, you can simply add one more Convert:
SELECT Convert(datetime, DateAdd(month, -1, Convert(date, GetDate())));
You may not need the explicit conversion to datetime, though.
Note: "One month ago from today" could be defined in many different ways. The way it works in SQL server is to return the day from the previous month that is the closest to the same day number as the current month. This means that the result of this expression when run on March 31 will be February 28. So, you may not get expected results in certain scenarios if you don't think clearly about the ramifications of this, such as if you performed the one-month calculation multiple times, expecting to get the same day in a different month (such as doing March -> February -> January).
See a live demo at SQL Fiddle
The demo shows the values and resulting data types of each expression.
Try like this..
select Cast(Cast(dateadd(month, -1, GETDATE()) as Date) as Datetime);
You can use this , it's pretty simple and worked for me -
SELECT SUM( amount ) AS total FROM expenses WHERE MONTH( date ) = MONTH( curdate() ) -1
To get the previous month start date and end date
DECLARE #StartDate date;
DECLARE #EndDate date;
select #StartDate= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
select #EndDate= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)
Here are many common dates you may need to pull with logic
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0) -- Today Midnight
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),-1) -- Yesterday Midnight
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)) -- First of Last Month
SELECT DATEADD(d,DATEPART(DD,GETDATE()-1),DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)) -- Same Day Last Month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) -- Last of Last Month
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) -- First of this month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- Last of this month
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- First of next month
SELECT DATEADD(d,DATEPART(DD,GETDATE()-1),DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- Same Day Next Month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)) -- Last of next month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+12,0)) -- Last of prior month one year from now
SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(DAY, 13-(##DATEFIRST + (DATEPART(WEEKDAY,GETDATE()) %7)), GETDATE())),0) -- Next Friday Midnight

How do I get the last possible time of a particular day

I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?
The answer is SELECT DATEADD(ms, -3, '2008-01-24'), the explanation is below.
From Marc's blog:
But wait, Marc... you said you like to use BETWEEN, but that query doesn't have one... that's because BETWEEN is inclusive, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server DATETIME columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:
SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0))
So to do the orders due this month as a BETWEEN query, you can use this:
SELECT [ID]
FROM [dbo].[Orders]
WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)
AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0))
Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't.
SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))
I thought you had c# at first.. I will leave this here in case anyone else stumbles across this.
DateTime now = DateTime.Now;
DateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);
You can replace the 'now' variable with whatever day you are trying to figure out
Add -1 milliseconds to the start of the next day (DateAdd even supports nanoseconds, if you want to get real fine).
But most likely you just want to use this value in a comparison, and in that case it's even simpler.
Rather than something like this:
AND #CompareDate <= [LastTimeforThatday]
or this:
#compareDate BETWEEN [StartDate] AND [LastTimeforThatday]
Do it like this:
AND #CompareDate < [BeginningOfNextDay]
or this:
AND (#CompareDate >= [StartDate] AND #CompareDate < [BeginningOfNextDay])
Why back into it?
SELECT DATEADD(ms, 86399997, *yourDate*)
I was able to use:
select {fn curdate()} + ' 23:59:59.000'
or
select DATEADD(ss,-1,DATEADD(DAY,1,CAST({fn curdate()} as DATETIME)))
to get the end of a day

Resources