How to search a date field using wild cards? - c#

I have a date search field in my ASP.Net application where the user enters the date he's looking for and the SQL query looks for the exact date provided.
I'm asked to allow the user to enter the date search using wildcards as follows:
- */12/2015 would mean get all the month of December, 2015
- */*/2015 would mean get all the year of 2015
- */*/* would mean get all the data you got
The only way I could think about to do this is to look in my C# code for '*' in the date, if it exists I will replace the query by a date range based on the position of the *.
This solution doesn't look practical to me, is there an easier way to do it in C# or SQL ?

the solution you found is the only one that makes sense while properly handling the information.
what you've been asked for is to give the users 'something' that allows them to search the dates as text and imho there are 2 possible solution:
the one you found (imho the 'right' one)
store the date as formatted string (BAD, AVOID, NIGHTMARE)
the wildcard approach would be simple to implement should you (wrongly, badly, poorly) store the date information and the format in a text field but this would prevent you from manipulating any date as a date and will put you in huge troubles at the first request that involves date handling (consolidation by month, calculate any rate in a given time span, etc...) or if you happen to have users in different countries (that expect a format different from the one stored into the text field).
implementing the search logic in the frontend the database will store the information using the correct data type and all the manipulation needed to accomplish the 'search the date as text' task are performed by the frontend that will feed to the RDBMS a set of parameters that allows it to handle the date properly.
the result would be as follows:
*/12/2015 --> between '20151201' and '20151231'
*/*/2015 --> between '20150101' and '20151231'
*/*/* --> no filter at all
if stored procedures are in use instead the result would be a couple of date parameters filled with the date values.

I would do as you already suggested and parse the search-string. Then depending on the search-string you can select your data. However you do not have to create dateranges, you can use YEAR and MONTH isntead.
Your SQL-Query could look something like this
SELECT * FROM YourTable WHERE YEAR(YourDate) = 2015 and MONTH(YourDate) = 12

In SQL you can replace * with % and use LIKE. Here is one example:
SELECT *
FROM (
SELECT cast('20150611' as date) as dateColumn
UNION
SELECT cast('20150610' as date)) as X
WHERE convert(varchar, dateColumn, 103) LIKE N'%/06/2015'
Keep in mind that this is practical and not the best solution from performance point of view.

Related

How to insert credit card expiration date in insert query in asp.net

I need to insert expiration date of credit card into database.
But i have only date and year dropdown.There is no dropdown for month.
If i am using this way then it gives error,because without month dateformat is wrong.
cmd.Parameters.AddWithValue("#ExpirationDate", dobday.Value & "-" & dobyear.Value)
Please suggest me how i can insert this in database.
You have three options.
The first is to modify your database so that the expiration date is a char(4). Then store it as MMYY. You don't need the dash or even day part for processing.
The second option is to modify your query so that you pass the day part as "1". So a CC that expires in December or 2012 would be 12/1/2012. Of course, your code should drop the day when you are doing something with it.
Personally, I'd go with option three. Don't store it at all. There is simply zero reason to store cc details in any database. Nearly all CC transaction providers provide much better ways of handling recurring transaction where your system doesn't have to keep that info around. If you are working with one that doesn't, then change providers as they are way behind the times. Otherwise you are playing with fire.
(from comments)
datatype of columns is datetime but here i am trying to insert by making them string
Yeah, don't do that. If the datatype is datetime, then construct a DateTime:
var expiry = new DateTime(/* whatever you need here using dobday / dobyear */);
cmd.Parameters.AddWithValue("#ExpirationDate", expiry);

When I convert date and time to only time, the cell becomes read only

I would like to understand the concept behind this.
I am making a database in c#. Now, I wish to have only date instead of date and time.
So, I went for the following command in sql query pane:
SELECT CONVERT(varchar, deal_start_date, 101) AS 'deal_start_date'
FROM client
The desired result comes but the data becomes read only and hence cant be edited.
Further, it does not stay permanently. I mean,
On clicking show table data again the date-time format comes.
Can any one tell me why the cells become read-only and how to keep the changes permanently through UI only??
Many thanks.
My guess on the read only part, is that since you are now converting the original value, you loose the link towards the column in the database. Just like a computed column can't be edited (how would you for example write to the column from the query that is defined as A+B as 'C'.
Inside what type of component are you showing this in your GUI? Maybe you can ahve your query remain as SELECT deal_start_date FROM client, and filter out the time part from your component?
Or, if you don't use the time in any other place in your application, change the column from datetime to date in the database.
I did not get a perfect answer but I found an alternative. I was trying with datetime datatype in MS SQL database. When I changed it to varchar(12), I got the desired result. i.e in date format.
(Thanks to insights provided by Øyvind Knobloch-Bråthen )
This is actually improper to follow as with size 12 in varchar, the time part is truncated.
(If the size of varchar is increased, the time part will be present)
But It served my purpose.
But I am still waiting for a correct answer,if any.

How to Search in the database according to Month and Year chosen from Combo Boxes?

I have an application where I register some information into the database where I have a Column (DateTime). In this column I insert the date from a DateTimePicker.
Now I want to make a search button which searches according to the date chosen from Comboboxes... but in this Comboboxes I left only one option, to select MONTH and YEAR... how can I make an SELECT query that selects all information according to the Month and Year chosen from the ComboBoxes?
select * from <table>
where month(searchDate)=Month_from_box and Year(searchDate)=Year_from_box
However, depending on the size of your data, this might not be the fastest approach. If you data is in the 100's or even 1000 rows, this approach might be OK...
Another approach would be to build starting and ending dates in C# from your input and then perform a range search
select * from <table>
where searchDate between Start_date_from_C# and End_Date_from_C#
If you go that approach, be sure to consider the time portion, make it 0 in first date and 23:59:59 in the End Date
If you have an index on the date field, the second approach will be faster...
All solutions which use either the datepart or month and year functions make it impossible for the server to optimize the query by using an index.
The only valid solution in terms of performance is #Sparkys second approach using the between clause. He also described the problems arising with the time fraction. That is why I would prefer using a plain date column (instead of datetime). Then you can write
select *
from YourTable
where DateColumn between <FirstDayOfSelectedMonthAndYear>
and <LastDayOfSelectedMonthAndYear>
because when using a datetime column and the range of
between '20121201' and '20121231 23:59:59'
Everything after the last second of the year and midnight still gets discarded. Although it is very unlikely it is technically not correct.
#Nicarus suggests widening the ending time to 23:59:59,997'. This seems to work but is 'ugly' (but, wtf, it works!)
Make sure you store the combo values into Integer variables in your C# before putting them in the SQL query. As others have alluded, SQL Injection attacks are possible if you allow the direct user input to be placed inside a SQL String.
Assuming you have 2 int variables "intMonth", "intYear", and the field name of "dateFieldname", the following SQL should work.
SELECT *
FROM [table]
WHERE datepart[mm,dateFieldname] = intMonth
AND datepart[yyy,dateFieldname] = intYear
Something like this
Select * from tablename where
datepart(mm,datecolumnname)=#cmboxMonthvalue nd datepart(yyyy,datecolumnname)=#ComboboxYearvalue

asp.net mvc datetime save to different db table depending on date

I want to save entries to a database table depending on the DateTime entered. I have a different model and partial view for each month in the year. Users can create events, I want the events to be saved to the corresponding month table in the db so I can return it to the correct view.
So I need some sort of if statement that says 'if the month value of the entered DateTime is x save to tabel x, if y save to y' and so on.
The user will navigate from month to month and pick dates from a html table styled like a calendar, so the entries need to be inserted to the section of the calendar that corresponds to the datetime. This is just to explain why I need this functionality.
If someone can reccomend a more elegant and functional method of achieving this, go right ahead!
I'm sorry I don't have code to post, I have tried a number of ways and failed. I will post code tomorrow morning when I'm at my computer, but this seems quite simple and I'm very new to this lark so if someone could shed light now, that would be great.
Thanks in advance!
Don't break it out into 12 separate tables. Store them in a single table. You could create a computed column that tells you the month number by calculating it from the DateTime value you're already storing. If your REALLY need to, you can create 12 views off of this table rather easily but I'd take the approach of adding time parameters to your query's WHERE clause. Make sure you index on the DateTime column.

Less than or Equal Date should not allow to enter

Using C# & Mysql
When i get the input date in the textbox it should compare with date from table, if it is equal it should throw error message, it should allow only the greater than date
For Example
Table1
ID Date
001 2010-08-05
002 2010-08-02
....
When i enter the date in the textbox like - 2010-08-04, it should compare with Date in the table1, if it is equal or less than max(date) from table1 then it should throw a error message, otherwise it should allow to insert a date.
Am new to mysql & c#, How to do this in c# & Mysql.
Need some code help.
I would first run a Query and fetch the max date to my front end application... Then depending on whether the application is a web application or windows application, I will use this value in Compare Validator (ASP.NET) or Textbox_Validating event to compare the values...
In case you are not familiar as to how to use Compare Validator or the Validating event, let me know, I can post some links here.
In case you want to put this restriction in your Table itself, you may need to use constraints / triggers... I dont know MySql much to help you here.

Categories