How to handle Dates correctly in SSMS - sql

Came across this issue in our scripts since the New year.
We have several scripts which look back 1 month from current UTC date.
Since the New Year, these scripts return zero results because, I assume, Sql doesn't see month 12 as being minus 1 from month 1.
Is there a way to force sql to see the year as the rotating data it is rather than an incremental line?
**Edit
Apologies, I forgot to add examples.
So, one line reads
Select .... Where ...
And month (timevalue) = month (getutcdate ()) -1
This gives zero results despite working correctly until January.
I've changed it temporarily to be = 12 which does return the correct data.
**Edit 2
Yep, thanks for the link and sample code. Works perfectly so far. I guess with our current setup it's not using daytime as I assumed, but instead using the month value as an int?

Check below, I hope it will help:
SELECT MONTH(DATEADD(MONTH, -1, GETUTCDATE())) AS PreviousMonth
returns:
PreviousMonth
12
So your query should be:
Select .... Where ... And month (timevalue) = MONTH(DATEADD(MONTH, -1, GETUTCDATE()))

Related

Report that updates yearly

I have created a report that is supposed to look at the number of baptisms at our church for the ministry year. The Ministry year runs from Aug 1 - July 31. I currently have the report set to tell me the names of anyone that has a baptism date greater than 8/1/2016. But I would need to change that year each year for it to report properly. so I wanted to use a Case statement to have it update each year, but i am getting an error message with this: (The error is in the where clause, so I didn't include the entire report)
WHERE (P.organization_id = 1) AND
((CandidateProcesses_BaptismDate68.datetime_value) between (
case
When datepart(month, getdate()) < 8 then ('8/1/'+ datepart(year, getdate()))
When datepart(month, getdate()) >7 then ('8/1/'+
datepart((year,getdate())-1))End) and Getdate())
Does anyone see why I am getting an error?
Thanks!
You are getting an error trying to add a string and a number. You could fix that using datename() rather than datepart(). But, I think this is a simpler approach:
WHERE (P.organization_id = 1) AND
year(dateadd(month, -7, CandidateProcesses_BaptismDate68.datetime_value)) = year(dateadd(month, -7, getdate()))
This subtract 7 months to get the "ministry year" and then compares that to the current date minus seven months. That is, it subtracts 7 months and then normalizes on the calendar year.
This is a bit more expensive than your version, because it cannot use an index on CandidateProcesses_BaptismDate68(datetime_value). However, I doubt the database of baptisms is so large that the query will take very long anyway. (If that is an issue, then your version can be made to work with some simple modifications.)

SQL issue: cannot construct data type date some of the arguments have values which are not valid

I am working on an Excel project where I use SQL query to extract some data from SQL Server 2012.
When I select the data without filters, everything works fine.
However, when I use the DATEFORMATPARTS formula below, I get this error:
Cannot construct data type date some of the arguments have values which are not valid
A.[Invoice date] is the correct date format.
WHERE
A.[Customer] NOT IN ('100', '398', 399)
AND A.[Item] LIKE '1%'
AND A.[Invoice date] >= DATEFROMPARTS(Year(DATEADD(yyyy, -1, GETDATE())), Month(DATEADD(yyyy, -1, GETDATE()) >) + 1, 1)
I've tried a lot of different stuff, but without luck.
Any guesses what is wrong in the above.
Thanks a lot in advance!
/ T
Thanks for the input
it was precisely the month: 12 + 1
that was the issue! thanks
You're going to have problems with that month calculation if you get a december and it adds a month to get month 13 of the year, this obviously isn't valid. If you want 11 months ago then do this;
DATEFROMPARTS(Year(DATEADD(YYYY,-1,GETDATE())),Month(DATEADD(mm,-11,GETDATE())),1)
Which (today, December 2016) returns '2015-01-01'
I believe > sign in the expression is a typo
Month(DATEADD(yyyy,-1,GETDATE()))+1
This is resulting 13 which is a invalid month so you are getting that error.
Removing > and +1 from Month part will fix your issue
select DATEFROMPARTS(Year(DATEADD(yyyy,-1,GETDATE())),Month(DATEADD(yyyy,-1,GETDATE())),1)
If you are trying to find last year last month first date then
select datefromparts(year(getdate())-1,12,1)

Pulling records based on Date in JDBC

How can I return all customers whose last appointment_date was 11 months ago from the date today? Or 12 months ago from the date in a month from today?
The first statement is working where I get the appointment from_date and compare it to the current date and return all the appointments that are happening tomorrow:
SELECT appointment.id,
appointment.from_date
WHERE (julianday('now') - julianday(appointment.from_date)) = 1
But for the second statement I cant figure out how to return all customers whose last appointment date was 11 months ago from the current date?
SELECT customer.id,
customer.last_appointment_date
FROM customer
WHERE datediff(month, customer.last_appointment_date, DATEADD(month, getDate())) = 12
datediff() doesn't work because I am using SQLite and it is not a recognised function.
Any help would be greatly appreciated.
EDIT: I am running these query's in my code in netbeans i am using the sqllitejdbc driver to run them through prepared statements
I have edited, its because i am running through netbeans, everytime i use datediff(month, customer.last_appointment_date, DATEADD(month, getDate())) = 12 it returns month not a valid column - it doesnt recognise it as a valid date part?
returned: Caused by: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such column: month)
Calculate the date to compare your field with, instead of calculating the difference and comparing to a constant, that way the database can make use of an index to locate records.
Use the date function instead of dateadd (see SQLite equivalent of SQL Server DateAdd function):
SELECT customer.id,
customer.last_appointment_date
FROM customer
WHERE customer.last_appointment_date = date('now', '-11 month')

Filter date to be greater than 24 months rather than 2 years?

This is what I have so far:
SELECT ListKey
FROM Closing_List
WHERE DATEPART(YEAR,closedate) > DATEPART(YEAR,GETDATE())-2)
But I want 24 Months back.
Thanks!
SELECT ListKey
FROM Closing_List
WHERE closedate > DATEADD(MONTH, -24, GETDATE())
SELECT ListKey
FROM Closing_List
WHERE closedate > DATEADD(MONTH,-24,GETDATE())
Using DATEADD is fine as long as you know what it's doing with the dates.
GetDate() returns the current date and time. Right now for me that's 08/30/2013 02:18:14pm
Passing that through DATEADD(MONTH,-24,GETDATE()) yields 08/30/2011 02:18:14pm'
So if I were running your query with that information it would be giving me all results with a closedate greater than (not equal to) 08/30/2011 02:18:14pm. There are a couple of things to consider about that.
For one, if you have records that closed on 08/30/2011 at 1:00pm then they won't be included in your results. Moreover if your close dates don't have times at all then you won't get any records from 08/30/2011.
Also note that if you run that query on 9/2/2013 then it won't include records from 9/1/2011. That may or may not be a problem, depending on your needs.
Another solution might be:
SELECT ListKey
FROM Closing_List
WHERE closedate >= dateadd(month,datediff(month,0,getdate())-24,0)
If you run the above anytime in September of 2013 it will include all records with a close date from September 2011 to September 2013. It doesn't care about what day of the month it currently is or if the close date includes time data.

MS Access SQL query for testing dates for last day of the quarter

OK, so I have a load of records in a table and they have many different dates.
I want to retern only those records whose date falls on the last day of whatever quarter it's in.
I.e. I basically need the equivalent of a lastDayOfQuarter(date) function that calculates the date that is the last day in the quarter for the date passed to it.
e.g. lastDayOfQuarter(#16/05/2013#) = #30/06/2013#
My query might look like:
SELECT * FROM mytable
WHERE mytable.rdate = lastDayOfQuarter(mytable.rdate);
This query will be run over PDO so no VBA allowed. Native MS Access only.
I would also prefer to not use string manipulation as there is a difference between US and EU dates which might cause issues down the line.
I'm answering myself as, with the help of HansUp answering a previous question of mine for finding month-end records, I found out quite an easy way to acheive this:
WHERE DateValue(m.rdate) = DateSerial(Year(m.rdate), Month(m.rdate) + 1, 0)
AND Month(m.rdate) IN(3,6,9,12)
the "last day of the quarter" could be different for different users. You may be best to build a table of "lastdays" based on your business rules, then use that table in your query.
And here as short answer...Try
Select DateAdd(day, -1, dateadd(qq, DATEDIFF(qq, 0, 'year-month-day'), 0))
For today it should give you
2013-06-30 00:00:00.000
SO for your Table you should use :
SELECT * FROM mytable
WHERE mytable.rdate = DateAdd(day, -1, dateadd(qq, DATEDIFF(qq, 0, mytable.rdate), 0));