SQL Query Between Dates in Visual Studio Table - mysql

I have a table within Visual Studio and I am wanting to create an input field in for a StartDate and another input field for an EndDate where a user selects a date for both and it will return all records that have a date that falls between the Start and End dates that the user chooses. I would also like the user to have the option to only search for the StartDate and leave the EndDate null so essentially only having 2 input fields for the table (or 1 if End Date is null).
I have this right now which returns the date the user selects but only on that date:
(Date = #Date) AND (#Date BETWEEN #StartDate AND #EndDate)
#StartDate is a date that comes before any date in the DB. #EndDate is the current day. This is just in case a user types in a date that is not within the date range of the database and it will return an error.
I have tried making the parameter #StartDate equal to #Date so when the user selects a date, it will make that the starting date. I also have the input field for the user to select an EndDate which seems to work. I just can't get the start date parameter to work like I want.
These are the queries I have tried:
1.
(Date = #Date) AND (#StartDate = #Date) AND (#Date BETWEEN #StartDate AND #EndDate)
2.
(Date = #Date) AND (#Date BETWEEN #Date AND #EndDate)
How do I modify this query/parameters to get the user to select a start date and an end date in input fields and for the table to return all the records that are between those dates?

(Date = #Date) AND ...
This will always require Date to equal #Date to be true, regardless of the rest unless some OR ... comes along.
Assuming the two fields fill #StartDate and #EndDate (to me it isn't clear, why there is a third variable, #Date) you're probably searching for something like:
#EndDate IS NULL
AND Date = #StartDate
OR Date BETWEEN #StartDate
AND #EndDate
If #EndDate IS NULL (the user hasn't put anything in the respective field) Date = #StartDate has to be true. Otherwise Date BETWEEN #StartDate AND #EndDate (which won't ever be true if #EndDate IS NULL just in case you wonder).

Related

SSRS: No Data Returned when Date Prompts used

If I use this in my dataset SQL:
DECLARE #StartDate DATE = '2018-01-01'
DECLARE #EndDate DATE = '2018-03-01'
The report runs and returns the expected Data.
When I comment out the #StartDate & #EndDate variables - delete the two parameters from the Report - and run the report using Date Prompts at run time [using the same Dates] - I get no data returned.
The Date field that I am attempting to filter on is a Datetime field.
I have tried the following two approaches in my SQL:
o.ORDERDATE >= #StartDate And o.ORDERDATE <= #EndDate
cast(o.ORDERDATE as DATE) >= Cast(#StartDate As Date) And cast(o.ORDERDATE as DATE) <= Cast(#EndDate As Date)
No data.
I added a Text Box to the Report Header and put the #StartDate Parameter value in there and got this: 01/01/2018 12:00:00 AM at run time.
I have gone back and forth a few times between uncommenting and commenting the Date variables at the top of the SQL. When I use the local variables - I get data. When I use the Date Parameters - no data.
I use Date Prompts in many of my other reports with no problems. I will go back and see if any of them is on this particular table and this particular date field - or if any of the other dates are Datetime fields ....
Meanwhile, I would appreciate any suggestions.
Thanks!
I would suspect a conversion issue comparing Date and DateTime types. To prove this, set the dates manually in your query to the full date and time. if this produces no results then try something simple like.
WHERE CAST(o.ORDERDATE AS Date) Between #StartDate AND #EndDate
Bear in mind that if you start your date with the year (I think) by default this is interpreted as being in YYYY-MM-DD format.

Given datetime, filter results by month of that datetime

For sql server 2008: what is the best way to filter results, to return only results that are in the same month as a certain date?
The best I could come up with is the following:
-- set up test data
DECLARE #TABLE1 AS TABLE (
ID INT,
STRING VARCHAR(MAX),
DATECOLUMN DATETIME
)
INSERT INTO #TABLE1
SELECT
0 ID,
'TABLE1 0' STRING,
CONVERT(DATETIME, '2016-10-13 12:45:00', 102) DATECOLUMN
UNION ALL SELECT 1, 'TABLE1 1', CONVERT(DATETIME, '2016-9-13 12:45:00', 102)
UNION ALL SELECT 2, 'TABLE1 2', CONVERT(DATETIME, '2016-10-1 00:00:00', 102)
UNION ALL SELECT 3, 'TABLE1 3', CONVERT(DATETIME, '2016-10-31 23:59:59', 102)
-- set up constraint
DECLARE #SOMEDATE DATETIME = CONVERT(DATETIME, '2016-10-13 12:45:00', 102)
-- filter
SELECT * FROM #TABLE1
WHERE MONTH(DATECOLUMN) = MONTH(#SOMEDATE)
Is this the best way?
Your query will return records where the month of DateColumn matches the month of #SomeDate, although (as #Jayvee points out) this would be true regardless of the year. So if that's what you want, your solution is fine.
But you asked whether that was the best solution. I would say no, because this won't take advantage of any index you may have that includes DateColumn.
So this is what I would do, if I were on SQL Server 2008:
declare #someDate datetime = GetDate()
declare #startDate date
declare #endDate date
-- I want the first day of the month, at 12:00:00AM (no time component).
-- The DateAdd expression subtracts days, and converting to the Date data type
-- ensures that I don't have a time component hanging around.
set #startDate = convert(date, DateAdd(day,- DatePart(day, #someDate) + 1, #someDate))
-- I want the first day of the next month. This is easy:
set #endDate = DateAdd(month, 1, #startDate)
-- Here's my actual query, that can take advantage of indexes that include DateColumn:
select *
from Table1
where DateColumn >= #startDate and DateColumn < #endDate
Note that I said >= for start date but < for the end date. That ensures that I'll pick up any date entries for the last day of the month that have a non-zero time component, but won't go into the next month.
The best way for a long-term solution is to create a date dimension table (you can find scripts out there to auto-generate one). The date dim table will just contain a list of dates as far back and forward as you care to go, and it includes columns like DayOfWeek, QuarterOfYear, YYYYMM, etc., so you can join CAST(YOURDATE AS DATE) to the date dim's date and pull nifty date info. Here you can join both of your tables to the date dim and use WHERE t1.YYYYMM = t2.YYYYMM.

Can we show Between date parameters displayed like below scenario

In my report contain FromDate and Todate Parameters,
but i need to display as drop down list below screen
When user clicks today it displays as today data,select IsBetween data displays as between data,
select this month displays as This month data like that needed.
Can anyone explain me How can i achieve this above type scenario in SSRS?
One way to do this is to pass the selected date description to your dataset query and have the appropriate dates calculated there before running the select statement. So the query would look something like this:
declare #StartDate date
declare #EndDate date
if #Date = 'Today'
BEGIN
#StartDate = GETDATE()
#EndDate = GETDATE()
END
SELECT *
FROM A
WHERE Date between #StartDate and #EndDate
And you would have to make sure you are passing the value of the Date parameter to the dataset like this:

How to use DATENAME in WHERE clause

Am using Sql Server 2008, I have a column named Date in my table, and I want to get the datas for the particular date.... I need to give this Date in my WHERE condition.
for example, if I want to get the records for the particular month in the given date, how can I use this Date in WHERE condition.
DATANAME(MONTH,'#Date')
if I give like this in my query I can get the month from the given DATE, the same way I tried by putting in WHERE condition like,
WHERE DATE= DATANAME(MONTH,'#Date')
here it reports conversion error...how can I display the datas for a particular month, can anyone help me
If you want a month of data for a table you should check against an interval. The query is not able to use indexes on the date column if you are applying functions on the column.
Use something like this to get data for April 2012.
-- The date parameter
declare #Date datetime
set #Date = '2012-04-11'
declare #FromDate datetime
declare #ToDate datetime
-- set FromFate to first of april
set #FromDate = dateadd(month, datediff(month, 0, #Date), 0)
-- set ToDate to first of may
set #ToDate = dateadd(month, 1+datediff(month, 0, #Date), 0)
select *
from YourTable
where [Date] >= #FromDate and [Date] < #ToDate
If you want to show data for a particular year and month you can use the YEAR and MONTH functions:
SELECT ...
FROM ...
WHERE YEAR(mydate) = 2012 AND MONTH(mydate) = 3 -- March, 2012
To me it seems that your field Date is not of type varchar or nvarchar, so using a condition where a Datetime = string is obviously wrong.
Have you tried
WHERE DATE= #Date
Shouldn't it be:
DATENAME(MONTH, #Date)
Instead of:
DATANAME(MONTH,'#Date')
(Notice "DATA" vs "DATE" and #Date isn't in quotations)
Then to use this against a date/datetime column you would have to cast both sides like below:
WHERE datename(Month, [Date]) = datename(Month, [Date])
Warning: The above does not use any indexes so isn't as efficient as "WHERE Date = Date"
First: Remove '' from variable. #Date, not '#Date'
If you want to find dates from specific month. (You have to remember about year condition also)
WHERE DATANAME(MONTH, #Date) = 'April'
if you want to find exact date:
WHERE DATE = #date

Finding Occurrences In The Future, Periods And Start Dates

Okay, I'll simplify this post.
I have a table "tasks" containing, for example, a task name, the date it starts, and a frequency. Based on these fields I need to be able to specify a date range and return each occurrence of that task for when it's due. For example, if I have a task with the frequency of M (for monthly) and my date range is today and a year in the future, then I will return twelve occurrences of that task from my output.
You'd think this is simply, but I've spent the last few days bleeding from my eyes trying to figure this one out. The output needs to also say when the task is next due.
How about something like this. You can expand the case to allow for other frequencies
DECLARE #Table TABLE(
TaskName VARCHAR(10),
StartDate DATETIME,
Frequency VARCHAR(10) --let say D,W,M daily, weekly, monthly
)
INSERT INTO #Table (TaskName,StartDate,Frequency) SELECT 'TADA', '15 Jan 2009', 'M'
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = '27 Nov 2009',
#EndDate = '27 Nov 2010'
;WITH cte AS(
SELECT TaskName,
StartDate,
Frequency
FROM #Table
UNION ALL
SELECT TaskName,
CASE
WHEN Frequency = 'M' THEN DATEADD(mm,1,StartDate)
END,
Frequency
FROM cte
WHERE StartDate <= #EndDate
)
SELECT *
FROM cte
WHERE StartDate BETWEEN #StartDate AND #EndDate
OPTION (MAXRECURSION 0)