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

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)

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.)

How to handle Dates correctly in SSMS

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()))

SQL query not pulling correct year

I have a query
SELECT
convert(varchar, dates, 101)
FROM
database
WHERE
dates BETWEEN '04/01/2015' AND '04/30/2015'
It returns all April dates but the problem is it is for every year (i.e. 2010, 2011, 2012, 2013, 2014, 2015). I think that it is not reading the last 2 digits of the year and just pulling everything from 2000 on. Am I correct in thinking this? How do I fix this?
Your dates column is likely not defined to be a date type. You can update the column type... or explicitly convert it in your query:
Select convert(varchar, dates, 101)
FROM database
Where convert(date,dates) BETWEEN '04/01/2015' and '04/30/2015'
The reason it would give you all April dates if your dates field was interpreted as a string of text is because all the April dates would be sorted together alphabetically. If it were properly interpreting your field to be a date, it would be able properly filter them.
You need to provide your dates in a standard format that SQL Server will understand correctly. See Correct way of specifying a given date in T-SQL.
For you it will be:
Where dates BETWEEN '20150401' and '20150430'
In tSQL this would work for you:
SELECT DATEPART(year, dates)
FROM [database]
WHERE DATEPART(MONTH, dates) = 4 AND DATEPART(year, dates)=2015;

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')

Getting week number of date in SQL

Is there a way to get the week number of a date with SQL that is database independent?
For example to get the month of a date I use:
SELECT EXTRACT(MONTH FROM :DATE)
But the EXTRACT function doesn't know about weeks in SQL92.
Please pay attention to the fact that I want a solution that is database independent! Do not misinterpret this as a question regarding MS SQL Server.
There doesn't appear to be a single standard SQL function to extract the week number from a date - see here for a comparison of how different SQL dialects can extract different dateparts from date fields.
You can try this.
declare #date datetime
select #date='2013-03-15 00:00:00'
select 'Week No: '+ convert(varchar(10),datepart(wk,#date)) as weekno
Try this one :
SELECT DATENAME(yy,GETDATE())+RIGHT(DATENAME(wk,GETDATE()),2)
To understand DATENAME, please follow this link : sqltutorials.blogspot.be/2007/05/sql-datename.html and for the right, suite101.com/article/sql-functions-leftrightsubstrlengthcharindex-a209089 . There are examples to better understand ;-) It will work on MS and other sql servers normally ;-)
The only db independent solution I see is to get the number of days between today and Jan 1 of curr. year. Then divide it by 7 and round it up. There is 73 days from Jan 1 till today, which gives 10.43 as week number. The ISO week number is 11.
Correction: the number of days between last day of the current week and Jan 1 of curr. year. In this case the ISO week is 10, and 68/7 = 10 (rounded).
The best idea I found is
SELECT ROUND(((DAY(NOW())-1)/7)+1)
select (DATEPART(yyyy , CAST(GETDATE() AS datetime)) * 100 +
DATEPART(ww , CAST(GETDATE() AS datetime))) as week