I have two dropdownlists, one with months and the other one with year. The user selects the submit month and year for the items they want to retrieve. In database the date is entered in full eg. 01/12/2009. There is an option for "All years" and "All months" in the dropdown lists but when users choose either they get null results. Many thanks. This is my query:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) LIKE ISNULL(#YearPay, ''))
AND (MONTH(Submit) LIKE ISNULL(#MonthPay, ''))
My parameter are:
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="" Name="YearPay" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="DropDownList2" DefaultValue="" Name="MonthPay" PropertyName="SelectedValue" />
Here's one way to solve the problem:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) = #YearPay OR #YearPay IS NULL)
AND (MONTH(Submit) = #MonthPay OR #MonthPay IS NULL)
That way, if you pass in NULL for either variable, that part of the WHERE clause will return true.
One fairly quick way is to make sure #YearPay and #MonthPay are INTEGER datatypes, then pass in (e.g.) -1 to indicate "ALL", so your query would become:
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (YEAR(Submit) = #YearPay OR #YearPay = -1)
AND (MONTH(Submit) = #MonthPay OR #MonthPay = -1)
However, for overall performance, I'd personally steer away from doing it in this way, using YEAR() and MONTH() as you won't get good index usage. Instead, I'd be tempted to change the query to just accept a date range, whereby the to and from dates are generated by your .NET code based on the selected dropdown items.
e.g.
SELECT ItemID, YEAR(Submit) AS SubmitYear, MONTH(Submit) AS SubmitMonth
FROM Items
WHERE (Submit >= #FromDate OR #FromDate IS NULL)
AND (Submit < #ToDate OR #ToDate IS NULL)
So, using the following examples for month/year selections:
Jan 2009 would result in #FromDate = '2009-01-01', #ToDate - '2009-02-01'
Any month, 2009 would result in #FromDate = '2009-01-01', #ToDate = '2010-01-01'
Any month, any year would result = #FromDate = NULL, #ToDate = NULL
Try this
select * from sys.tables where name like ''
and this
select * from sys.tables where name like '%%'
That being said, I totally agree with Nebakanezer's comment (and solution).
Related
I am a new developer in asp.net, I want to create query that retrieve row based on comparing between DateTime (column in my table) with the current date, I used a lot of things like:
Select * from employee where DateTime = dateadd(dd,0, datediff(dd,0, getDate()))
Select * from employee where DateTime=Convert(date, getdate())
Select * from employee where DateTime =getDate()
The first one, worked correctly but suddenly did not work!
what do you think is the problem?
Try your query like this
Select * from employee where convert(date,yourfield) = convert(date,dateadd(dd,0, datediff(dd,0, getDate())))
You can use CASTto trim time part from the date for the sake of searching.
SELECT * FROM Employee WHERE CAST(DateTime AS DATE) = CAST (GETDATE() AS DATE)
select DATE(Orders.OrderDate,'10 DAY') from Orders. it will give the following result "1996-07-14"
When using column name directly instead of value in numeric it will give the empty result
select DATE(Orders.OrderDate,'Orders.OrderId DAY') from Orders.
What wrong with the above select query?
Try concatenating a string using the OrderId column:
SELECT DATE(Orders.OrderDate, '+' || Orders.OrderId || ' DAYS')
FROM Orders
You want a query of the form
SELECT DATE(Orders.OrderDate, '+7 DAYS') FROM Orders
and string concatenation will let you achieve that.
I am currently working on a website that offers tutoring services and I have been stuck on this issue quite a while..
I have 2 text boxes where the user chooses a start date and a finish date, when the user clicks view he would be suppose to see the results in a gridview. I am using FormParameters to insert the date into the query.
SelectCommand of the sqldatasource
SelectCommand="SELECT [Session].Session_num AS Num, [Session].Session_Time_Stamp AS Session_Date, Student.Student_First & ' ' & Student.Student_Last AS Student FROM (([Session] INNER JOIN Student ON [Session].Student_Num = Student.Student_Num) INNER JOIN Class ON [Session].Class_ID = Class.Class_ID) WHERE ((([Session].Session_Time_Stamp) Between #firstdate And #seconddate))">
Parameters of the SqlDataSource
<SelectParameters>
<asp:FormParameter Name="firstdate" Type="DateTime"/>
<asp:FormParameter Name="seconddate" Type="DateTime"/>
</SelectParameters>
This is executed when the user clicks the view button, it is where I set the values of the parameters and execute the sql select.
Dim fdate As DateTime = Format(CDate(txtStartDate.Text), "MM/dd/yyyy")
Dim ldate As DateTime = Format(CDate(txtEndDate.Text), "MM/dd/yyyy")
gridTutor.SelectParameters("firstdate").DefaultValue = fdate
gridTutor.SelectParameters("seconddate").DefaultValue = ldate
gridTutor.Select(DataSourceSelectArguments.Empty)
gridTutorSessions.DataBind()
fdate and ldate are not empty, however after this is executed the query result is empty. Could it be that wrong methods to execute the select?
Edit: I realized the problem is probably with the query and DateTime format. When I transformed my textbox value to DateTime it put it like this #2/20/2014#. However, it doesn't return anything even if there are values between the two dates.
If anybody have an access query with DateTime I would like to see it. Thanks
I managed to fix it by formatting the date in my access database it's not the best solution but it is a fix for the situation
I believe you need to manually set fdate and ldate just before you do your 'selectparameters' (i.e. use "fdate = Format(CDate(txtStartDate.Text), "MM/dd/yyyy")". According to the following, values asigned to Dim in the manner you have would not reflect the realtime values you want. See the following regarding VB: "You can assign a value to a variable when it is created. For a value type, you use an initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can be calculated at compile time.
I want to filter the gridview by comparing a datetime column of type datetime in sql server with a date textbox.
The datetime column in sql server is being stored/displayed (as default) in the yyyy-mm-dd hh:mm:ss.sss format.
However the date textbox is in the format dd/mm/yyyy.
<asp:TextBox ID="date_tb" runat="server" TextMode="Date"></asp:TextBox>
I tried using
FilterExpression="CONVERT(VARCHAR, [ScheduledDateTime], 105) LIKE '%{0}%'">
but it didn't work.
FilterExpression="CONVERT([ScheduledDateTime], 'System.String', 105) LIKE '%{0}%'">
also did not work.
I then tried using
SelectCommand="SELECT [ScheduledDateTime], CONVERT(VARCHAR, [ScheduledDateTime], 105) as d ... FROM table1
FilterExpression="d LIKE '%{0}%'">
but it didn't work as well.
edit:
I have changed the ControlParameter into <asp:ControlParameter Name="ScheduledDateTime" ControlID="date_tb" PropertyName="Text" type="DateTime"/> so I no longer have to be concerned about the date format.
Although now there is a problem to comparing date with datetime.
This is what you can do
select * from MyTable where convert(varchar, a, 103) = '03/24/2013'
You probably don't want to compare date to the seconds. The right side of equasion comes from the textbox
If you want it really good, then do this
Dim sql as String = "select * from MyTable where convert(varchar, a, 103) = #1"
#1 is a parameter that you want to add to Command Object and it will have value of your textbox.
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Use format 103 to convert a 'dd/mm/yyyy' string to a date. You are using 105, which is 'dd-mm-yyyy'
You should not need to do any string conversion to compare DateTimes in SQL. When you use LIKE, SQL will convert the DateTime into a string value and you need to make sure that you're using the same format on both ends. If your source data does not include any time component, then you should just be able to do:
FilterExpression="ScheduledDateTime = {0}"
If it does include time components and you want to truncate the time, you can try:
FilterExpression="dateadd(dd, datediff(dd,0, ScheduledDateTime ), 0) = {0}"
or
FilterExpression="ScheduledDateTime BETWEEN {0} AND dateadd(dd, 1, {0})"
I have a query that searches by date. the dates in the database include the time. How do I search on just the date only.
select *
from weblogs.dbo.vwlogs
where Log_time between #BeginDate and #EndDAte
and (client_user=#UserName or #UserName Is null)
order by Log_time desc
cmd.Parameters.AddWithValue("#BeginDate", txtBeginDate.Text);
cmd.Parameters.AddWithValue("#EndDAte", txtEndDate.Text);
Leave your sql mostly as is and just fix your parameters:
cmd.Parameters.Add("#BeginDate", SqlDbType.DateTime).Value =
DateTime.Parse(txtBeginDate.Text).Date;
cmd.Parameters.Add("#EndDAte", SqlDbType.DateTime).Value =
// add one to make search inclusive
DateTime.Parse(txtEndDate.Text).Date.AddDays(1);
You also want to check to make sure your textboxes are valid datetimes first, but you should get the idea.
The only caveat here is that due to a quirk with the BETWEEN operator it will match the first instant of the next day. So, to fix that we write the query like this:
SELECT *
FROM vwlogs
WHERE Log_time >= #BeginDate AND Log_Time < #EndDate
AND (client_user=#UserName OR #UserName IS NULL)
ORDER BY Log_time DESC
Pay special attention to the comparision operators around the date.
The first thing to do is to remove the times from the dates. If you want to do this in the sql server code you can use something like the code below. I have this as a function on all the databases I work on
cast(floor(cast(#fromdate as float)) as datetime)
The next thing to worry about is the where criteria. You need to make sure you select everything from the start of the from date to the end of the to date. You also need to make sure queries for one day will work which you can do with a date add like this
Where LogTime >= #fromdate and LogTime < DateAdd(dd, 1, #todate)
In SQL round the start and end date to Whole Dates and use >= #BeginDate and very specifically < #EndDAte. The "rounding" process is not very elegant I'm afraid
e.g.
SELECT #BeginDate = DATEADD(Day, DATEDIFF(Day, 0, #BeginDate), 0),
#EndDAte = DATEADD(Day, DATEDIFF(Day, 0, #EndDAte) + 1, 0)
select *
from weblogs.dbo.vwlogs
where Log_time >= #BeginDate
and Log_time < #EndDAte
and (#UserName Is null OR client_user=#UserName)
order by Log_time desc
Note that I've moved "#UserName Is null" first, as there is some evidence that this test will easily pass/fail, and will cause the second more CPU intensive test (client_user=#UserName) to be ignored if the first test is TRUE (may be TommyRot of course ...)
Also, for best performance, you should explicitly name all the columns you need, and not use "SELECT *" (but that may just have been for the purpose of this question)
If you want to change the sql instead,
TRUNC(Log_Time) will reduce every datetime to to that date at midnight.
Make sure that you build your index on the column as TRUNC(Log_TIME) so it's usable.
Another gotcha - truncating your end date will NOT include that date! Consider:
WHERE Log_Time >= #BeginDate AND Log_Time < #EndDate
If #EndDate is truncated it will be midnight and not match anything on that day. You'll need to add a day!
Clean up the dates by adding the following line before your query...
select
#begindate=dateadd(day,datediff(day,0,#begindate),0),
#enddate=dateadd(ms,-3,dateadd(day,datediff(day,0,#enddate),1))
This will floor your begin date to the lowest possible time (00:00:00.000), and ceiling your end date to the highest possible (23:59:59.997). You can then keep your BETWEEN query exactly as it was written.
select *
from weblogs.dbo.vwlogs
where Log_time between #BeginDate and #EndDAte
and (client_user=#UserName or #UserName Is null)
order by Log_time desc
Hope this helps.