SQL automatic date range using DateSerial function - sql

We've been using MS Access, with the following syntax for MTD Data that works for us:
Between DateSerial(Year(Date()),Month(Date()),1)
And DateSerial(Year(Date()),Month(Date())+1,0)
We need to transition the above logic to SQL/SSRS for automatic emailed reports, but I cannot get this DateSerial logic to work with SQL.
In the Filter field of the SQL query, I can successfully use BETWEEN '8/1/2014' AND '8/31/2014' for MTD data, but would like to have a DateSerial logic applied so that reports don't need to be created for every month, quarter, year, etc.
When trying to use the DateSerial function, we get the error "Invalid or missing Expression". I've seen a few topics on this that Parameters are required, but really believe that this is a simple syntax issue for the filter field, since actual dates work with the BETWEEN command.

There are several different ways to get this. Here is just one way.
Get todays date. In this case 8/27/2014
Declare #Today date = cast(getdate() as date)
Get the first of the month, 26 days in the past
Declare #StartDate date = dateadd(d, -1 * (day(#Today) - 1), #Today)
select #Today, #StartDate

You can use the function CONVERT:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Or the function DATEFROMPARTS if you are using SQL Server 2012:
http://msdn.microsoft.com/en-us/library/hh213228.aspx
Or DATEADD:
select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0); -- first day of current month
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()), -1) -- last day of current month
This last one I took from: https://stackoverflow.com/a/11746042/1274092
See mine at:
http://sqlfiddle.com/#!3/d41d8/38333

This has been resolved. The ODBC driver does not apparently play well with SSRS. The DateSerial command would not work within the query itself. The workaround was to add the filter to the Dataset. This syntax is what works, but again only in the Dataset filter: [expression] Between [first value box] =DateSerial(Year(Now()),1,1) [second value box] =DateSerial(Year(Now()),12,31)
This gives us the YTD reporting data that we require.

Related

How can I get a timestamp or a data using datediff function?

I am reading some sql code from somebody where DATEDIFF function should return a timestamp. Here is the code:
DATEDIFF(wk, 6, GETDATE())
I do not see any sql syntax like this anywhere. Can anyone explain how this code should return date or timestamp?
You use DATEDIFF() function to get the difference between two dates, and it returns integer value. Looking at what you are trying to do, it seems you want to add 6 weeks to the current date. In such cases you should use DATEADD() function instead.
Below are some some examples:
SELECT DATEADD(ww, 6, GETDATE()),
DATEDIFF(ww,'6/1/2022', getdate())

Query data from previous day when month/year changes

In a SQL Server query, I am currently using the clause
WHERE
DAY(trade_date) = DAY(GETDATE()) - 1
AND MONTH(trade_date) = MONTH(GETDATE())
AND YEAR(trade_date) = YEAR(GETDATE())
to query my data from the previous day.
It is working fine right now but my question is if, for example, on 8/1/2021, SQL Server will try to get data from 8/0/2021 or if it will know to get data from 7/31/2021.
If this query won't work what could I use instead? Thanks!
I would recommend using proper date comparison logic - instead of breaking it down to day, month and year. Also, it is recommended to use proper date arithmetic functions like DATEADD instead of just - 1 on your date values (never sure what that -1 stands for: minus one day? Week? Month? Hour?).
And lastly - I would also recommend using SYSDATETIME() instead of GETDATE() since the latter always returns a DATETIME datatype - which should be on its way out, and you should use DATE (if you don't need to time portion), or DATETIME2(n) (if you do need the time portion) since those are more efficient and have fewer limitations compared to DATETIME.
If your trade_date is a DATE column (as it probably should be), just use:
WHERE
trade_date = DATEADD(DAY, -1, SYSDATETIME())
and if it's not a DATE - just cast it to a date as needed:
WHERE
CAST(trade_date AS DATE) = DATEADD(DAY, -1, CAST(SYSDATETIME() AS DATE))

DateAdd function in Excel SQL query not working

I am using Excel to make an SQL query (connecting to an ODBC).
I have a problem with the function DateAdd(), which just doesn't work as expected.
What I need to do is to get the data from the last six months.
My code is something like
SELECT blablabla
FROM blablabla and then I have this:
WHERE Note_0.Relate_key = Work_history_0.WO_Key AND Work_history_0.Order_date> DateAdd(Month, -6, Now())
I've searched in the internet and this syntax is supposed to work, but I get this error message
Column "MONTH" cannot be found or is not specified for query. (13865)
As if it didn't have the parameters I think it has, which are "interval, number, date", but something else.
Any idea about this?
This is what you need:
DateAdd("m", -6, Now)
Or even DateAdd("m", -6, Date), if you want to get rid of the hours, coming from Now.
Thus, you have to declare that you want the "Months" to be substracted.
DateAdd MSDN
WHERE Note_0.Relate_key = Work_history_0.WO_Key AND Work_history_0.Order_date > ADD_MONTHS(curdate(), -6)

Function get the last day of month in sql

I need to get the last day of month with input of month and year. For example, with input 06/2016 it will return 30. I use SQL Server 2005. Thanks for any help.
Suppose your input is VARCHAR in the form of MM/YYYY.
Use RIGHT and LEFT to get the year and month respectively. Then use DATEFROMPARTS to generate the starting date. Next, use EOMONTH to get the last day of the month. Finally use DAY to extract the day part.
DECLARE #input VARCHAR(7) = '06/2016'
SELECT
DAY(
EOMONTH(
DATEFROMPARTS(CAST(RIGHT(#input,4) AS INT),CAST(LEFT(#input, 2) AS INT),1)
)
)
The above only works for SQL Server 2012+.
For SQL Server 2005, you can use DATEADD to generate the dates:
SELECT
DAY( -- Day part
DATEADD(DAY, -1, -- Last day of the month
DATEADD(MONTH, CAST(LEFT(#input, 2) AS INT), -- Start of next month
DATEADD(YEAR, CAST(RIGHT(#input, 4) AS INT) - 1900, 0) -- Start of the year
)
)
)
Reference:
Some Common Date Routines
You would do something like this:
select eomonth(getdate(), 0);
If you want it formatted as MM/YYYY then you'd do this:
select format(eomonth(getdate(), 0), 'MM/yyyy');
Pardon me for tossing-in a response that is not specific to "SQL Server," nor thence to "2005," but the generalized way to compute the answer that you seek is as follows:
Break down the input that you have, e.g. 06/2016, into two parts. Call 'em #MONTH and #YEAR. Define a third value, #DAY, equal to 1.
Typecast this into a date-value ... "June 1, 2016."
Now, using the date-handling functions that you're sure to have, "first add one month, then subtract one day."
One thing that you must be very careful of, when designing code like this, is to be certain(!) that your code for decoding 06/2016 works for every(!) value that actually occurs in that database, or that it can be relied upon to fail.
try this,
declare #input varchar(20)='06/2016'
set #input=#input+'/01'
declare #dtinput datetime=#input
select dateadd(day,-1,dateadd(month,datediff(month,0,#dtinput)+1,0))
--OR in sql server 2012
select eomonth(#dtinput)

SSRS: Creating a difference between the beginning of the day to the execution time

I am having a bit of an issue with my SSRS report I am trying to run. I am trying to have a report pull from the beginning of the day (to be ran daily) and the execution time.
I have:
(Rest of the SQL here)WHERE fa.ReceivedDate between #prmStartDate and %executionTime
In #prmStartDate currently I have =DateValue(today) which is creating an error when running.
Would this not work?
where ReceivedDate >= cast(getdate() as date)
and ReceivedDate < getdate()
If it will always use the current date, then you could use the GETDATE function in SQL server and you just need a way to strip off the time portion on the first date. A method I like is suggested here.
Your code would look like this:
(Rest of the SQL here)WHERE fa.ReceivedDate between DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) and GETDATE()
If you want to allow the user to choose a different day's data, just add a parameter instead of the GETDATE function:
(Rest of the SQL here)WHERE fa.ReceivedDate between #DateParam and DATEADD(dd, 1, #DateParam)