How to do select query between dates of two datetime picker? - c#

I have to datetimepickers FromDate and ToDate, and want to do select data between to dates,
I have written the query
select * from tbl where pDate>='" + dtpFrom.value + "'and pDate<='" + dtpTo.value + "'");
This query giving error
Data type mismatch in criteria expression
But datatype is Date/Time in ms access table.

Looks like you try to put single quotes for your DateTime values. # for dates and ' for strings but they required for literal SQL queries.
If you use parameterize queries, you will not need them.
using(var con = new OleDbConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select * from tbl where pDate >= ? and pDate <= ?"
cmd.Parameters.AddWithValue("?", dtpFrom.Value);
cmd.Parameters.AddWithValue("?", dtpTo.Value);
...
...
}

Related

date is not compare to database where combobo selected item

I am creating a project that user have to select the date in Combobox but where I have select that date in Combobox that is displaying the error date
String was not recognized as a valid DateTime.'
I am trying to fetch date from database in slq.
Below is my code
System.Data.DataTable dt;
SqlConnection con=new SqlConnection(#"Data Source=krupal;Initial Catalog=LOANNOTICE;Integrated Security=True");
con.Open();
this.cmbmonth.FormatString = "yyyy/ MM/dd";
// DateTime dat = Convert.ToDateTime(cmbmonth.SelectedItem.ToString("yyyy/MM/dd"));
//var date = cmbmonth.Text;
//var d1 = Convert.ToDateTime(cmbmonth.Text);
// MessageBox.Show("" + d1);
string Querie=("SELECT HCODE ,(select top 1 rtrim(Name) From RNSB_TEST.dbo.FC014076 p with(nolock) where convert(varchar,PrdCd) = convert(varchar,HCODE)) as PrdName,count(*) as NoOfAcc,round(Sum(BAL2802),2) as PrintAmt ,round(SUM(IntAmt),2) as TotalInt,0 as TDSAmount, round(SUM(IntAmt),2) as NetIntAmt, round((Sum(BAL2802) + SUM(IntAmt)),2)as TotalAmt from LOANNOTICE.dbo.UNCLAIM_DEPO with(nolock) where EffeDate='"+Convert.ToDateTime(cmbmonth.SelectedText).ToString("yyyy/MM/dd") + "' group by HCODE union SELECT HCODE, (select top 1 rtrim(Name) From RNSB_TEST.dbo.FC014076 p with(nolock) where convert(varchar, PrdCd) = convert(varchar, HCODE)) as PrdName,count(*) as NoOfAcc,round(Sum(MatAmt), 2) as PrintAmt ,round(SUM(IntAmt), 2) as TotalInt,round(sum(TDS_Amount), 2) as TDSAmount, round(SUM(Net_Int), 2) as NetIntAmt, round((Sum(MatAmt) + SUM(Net_Int)), 2) as TotalAmt from LOANNOTICE.dbo.UNCLAIM_DEPO_TDR with(nolock) where EffeDate = '"+Convert.ToDateTime(cmbmonth.SelectedText).ToString("yyyy/MM/dd") + "' group by HCODE");
SqlCommand cmd = new SqlCommand(Querie, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dt = new System.Data.DataTable();
sda.Fill(dt);
Anyone have a solution please let me know fast.
Thanks.
You need to parse string into valid date time.
Your conversion was wrong, please convert string to date time and then pass to appropriate date fields.
please refer this link .
It draws my attention that you have this blank space here:
this.cmbmonth.FormatString = "yyyy/ MM/dd"
Anyway, you should always check dates passed as string, and throw an exception if you can't cast them:
if (!DateTime.TryParse(_date, out DateTime date))
{
throw new InvalidCastException("Not a valid date.");
}
And last, try to set you SqlCommand parameters this way, is more readable and you don't have to deal with string interpolation (checkout for:
using (DbConnection connection = new SqlConnection("MyConnectionString"))
{
using (DbCommand command = new SqlCommand(connection))
{
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM MyTable WHERE Date = #Date";
command.Parameters.Add("#Date", SqlDbType.Date);
command.Parameters["#Date"].Value = date;
}
}
Give it a try! :)
Regards!

Trying to pull records in between two time ranges from SQL Server

I want to display a count on a label for all the rows that fall between 6AM and 8AM. I have a datetimepicker that I want to also use to select the day for all the rows that should be counted. I have tried several different ways to format my SELECT statement but nothing has worked. I either get datetime conversion error or wrong syntax.
var sql = "SELECT RTFPressTableID" +
"FROM RTFPressTables" +
"WHERE PressCloseTime BETWEEN CONVERT(DATE, 'Date 06:00:00:000 AM',109) >= #Date AND CONVERT(DATE, 'Date 08:00:00:000 AM',109) <= #Date";
using (SqlConnection conn = new SqlConnection("Data Source = ; Initial Catalog = ; Integrated Security = True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#Date", SqlDbType.DateTime);
command.Parameters["#Date"].Value = dateTimePicker1.Value.Date;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
What date time should "'Date 06:00:00:000 AM'" represent?
And why do you use "BETWEEN" and then ">=" resp. "<=" in it's arguments? That's not the right syntax. Either use BETWEEN or >= and <=. Though I guess < is actually what you want for the second operator.
You probably want:
var sql = #"
SELECT RTFPressTableID
FROM RTFPressTables
WHERE PressCloseTime >= dateadd(hour, 6, #Date)
AND PressCloseTime < dateadd(hour, 8, #Date);";
...
I think you want the following:
var sql = #"SELECT RTFPressTableID
FROM RTFPressTables
WHERE PressCloseTime BETWEEN DATEADD(day, DATEDIFF(day, 0, #Date), '06:00:00') AND DATEADD(day, DATEDIFF(day, 0, #Date), '08:00:00')";
using (SqlConnection conn = new SqlConnection("Data Source = ; Initial Catalog = ; Integrated Security = True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#Date", SqlDbType.Date);
command.Parameters["#Date"].Value = dateTimePicker1.Value.Date;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
Which has 3 changes from your code:
Spaces are added to the SQL string as mentioned in the comments. In fact using a multi-line string (verbatim string literal) which is much easier to use for SQL strings.
The datatype of the #Date parameter is now of type date instead of datetime.
Most importantly the between statement is corrected to add the times to the date provided and use them as the limits.
Ref: Add Time to DateTime
You need to give spaces in your quotation marks after plus to avoid string concatenation. Something like this:
"SELECT RTFPressTableID" +
" FROM RTFPressTables" +
" WHERE PressCloseTime

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. SqlException

I am a beginner in asp.net. I am using a query :
string num = ("SELECT count(*) from booking WHERE date='" + dt + "' AND start_time='" + stime + "' AND end_time='" + etime + "' AND lid='" + hostloc + "'");
SqlCommand cmd = new SqlCommand(num, con);
con.Open();
int count = (int)cmd.ExecuteScalar();
con.Close();
Sometimes when i submit my web form it gives me an SqlException :
"The conversion of a char data type to a datetime data type resulted
in an out-of-range datetime value."
This does not happen always!!
Please, any help is appreciated..
Thank You in advance
string num = "SELECT count(*) from booking WHERE date=#dt AND start_time=#stime AND end_time=#etime AND lid=#hostloc";
using(SqlCommand cmd = new SqlCommand(num, con))
{
cmd.Parameters.AddWithValue("dt", dt);
// etc for all params
con.Open();
int count = (int)cmd.ExecuteScalar();
}
Note this assumes dt is a DateTime etc.
This solves multiple problems, including formatting, localisation and SQL injection.
First of all use parameterized queries for your SQL calls or you might get SQL injected soon enough.
Also you need to convert dt to datetime before you send the variable to the SQL Server in order to avoid such errors, like Convert.ToDatetime(dt).

How to select data between two date ranges using datepicker c#

Using Visual studio coding C# I have a windows form and have two datetime pickers, how would I select two different date ranges and retrieve data from my SQL database. This is what I have done so far...
SqlConnection ssl = new SqlConnection();
ssl.ConnectionString = #"connection goes ";
ssl.Open();
var a = dateTimePicker1.Value.ToString("yyyy-MM-dd");
var b = dateTimePicker2.Value.ToString("yyyy-MM-dd");
SqlDataAdapter ad = new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >='" + a + "' AND modified_time <= '"+ b +"'", ssl);
DataTable dt = new DataTable();
ad.Fill(dt);
dataGridView1.DataSource = dt;
When you do this:
"... >= '" + a + "' AND ..."
You're creating a string literal that has your date value in it. The database won't treat it as a date though, and if the query executes it won't do what you want.
Instead, parameterize your query, which is the correct way to pass the dates (or any other values) in:
SqlDataAdapter ad =
new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >= #Date1 AND modified_time <= #Date2", ssl);
ad.SelectCommand.Parameters.AddWithValue("#Date1", dateTimePicker1.Value);
ad.SelectCommand.Parameters.AddWithValue("#Date2", dateTimePicker2.Value);

Weird bug when inserting DateTime to sql server 2008

I'm inserting a datetime field to sql server. From my local computer it works just fine. example: the datetime field in sql server is : "2013-07-31 08:00:00.000", but when I run the application form the server it switches the day and month and insert it like this:
"2013-07-31 15:15:00.000".
My relevant page loads some entries from the sql server depending on today's date.
Like this:
public List<act_event> return_event_list(DateTime date) //return all events for spesific date
{
List<act_event> event_list = new List<act_event>();
String date_sql = date.ToString("yyyy-MM-dd");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where '" + date_sql + "'>=(CAST(e_start as DATE)) and '" + date_sql + "'<=(CAST(e_end as DATE))"))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
act_event a_event = new act_event();
a_event.e_num = Convert.ToInt32(rdr["e_num"]);
a_event.name = rdr["e_name"].ToString();
a_event.start = Convert.ToDateTime(rdr["e_start"]);
a_event.end = Convert.ToDateTime(rdr["e_end"]);
a_event.description = rdr["e_description"].ToString();
a_event.address = rdr["e_address"].ToString();
event_list.Add(a_event);
}
}
}
}
return event_list;
}
This is how I insert the datetime fields:
public void add_event(act_event add_avent)
{
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "insert into act_events values(#e_name, #e_start, #e_end, #e_description, #e_address)"))
{
cmd.Parameters.AddWithValue("#e_name", add_avent.name);
SqlParameter param2 = new SqlParameter("#e_start", SqlDbType.DateTime);
param2.Value = add_avent.start;
cmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#e_end", SqlDbType.DateTime);
param3.Value = add_avent.end;
cmd.Parameters.Add(param3);
//cmd.Parameters.Add(new SqlParameter("#e_start", SqlDbType.DateTime));
//cmd.Parameters["#e_start"].Value = DateTime.Parse(add_avent.start.ToString());
//cmd.Parameters.Add(new SqlParameter("#e_end", SqlDbType.DateTime));
//cmd.Parameters["#e_end"].Value = DateTime.Parse(add_avent.end.ToString());
cmd.Parameters.AddWithValue("#e_description", add_avent.description);
cmd.Parameters.AddWithValue("#e_address", add_avent.address);
cmd.ExecuteNonQuery();
}
//using (SqlCommand cmd2=create_command
}
}
I tried changing the select command, adding this:
using (SqlCommand cmd = create_command(con, "select * from act_events where ( '" + date_sql + "'>=(CAST(e_start as DATE)) and '" + date_sql + "'<=(CAST(e_end as DATE)) ) or ( '" + date_sql2 + "'>=(CAST(e_start as DATE)) and '" + date_sql2 + "'<=(CAST(e_end as DATE)) ) "))
but for some of the dates it gives me an error:
Conversion failed when converting date and/or time from character
string.
What should I do?
EDIT:
I tried to run the query from the sql studio itself like this:
select * from act_events where ( '2013-08-03'>=(CAST(e_start as DATE)) and '2013-08-03'<=(CAST(e_end as DATE)) ) or ( '2013-03-08'>=(CAST(e_start as DATE)) and '2013-03-08'<=(CAST(e_end as DATE)) )
it gives me:
But if I run it like this: (different date)
select * from act_events where ( '2013-07-30'>=(CAST(e_start as DATE)) and '2013-07-30'<=(CAST(e_end as DATE)) ) or ( '2013-30-07'>=(CAST(e_start as DATE)) and '2013-30-07'<=(CAST(e_end as DATE)) )
it gives me this error:
EDIT2:
After James suggestion I made a parameterized query like this:
String date_sql = date.ToString("yyyy-MM-dd");
String date_sql2 = date.ToString("yyyy-dd-MM");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where #date1>=(CAST(e_start as DATE)) and #date2<=(CAST(e_end as DATE))"))
{
cmd.Parameters.AddWithValue("#date1", date_sql);
cmd.Parameters.AddWithValue("#date2", date_sql);
cmd.Parameters.AddWithValue("#date3", date_sql2);
cmd.Parameters.AddWithValue("#date4", date_sql2);
which still won't load the correct entries from the sql server
Then I tried this query:
String date_sql = date.ToString("yyyy-MM-dd");
String date_sql2 = date.ToString("yyyy-dd-MM");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where ( #date1>=(CAST(e_start as DATE)) and #date2<=(CAST(e_end as DATE)) ) or ( #date3>=(CAST(e_start as DATE)) and #date4<=(CAST(e_end as DATE)) )"))
{
cmd.Parameters.AddWithValue("#date1", date_sql);
cmd.Parameters.AddWithValue("#date2", date_sql);
cmd.Parameters.AddWithValue("#date3", date_sql2);
cmd.Parameters.AddWithValue("#date4", date_sql2);
And again it just give me:
Conversion failed when converting date and/or time from character string.
It's never ever really a good idea to try pass date/time's to SQL as string from the client unless you are absolutely certain of the server locale.
Switching to a parameterized query should resolve your issue.
The problems you encounter are due to string to date conversions in one point or another, both on the client and the server's side
You don't need to do any conversionf to string or date if you use a parameterized query and you pass DateTime values, provided of course that the type of your table's fields is also a date type.
The following code makes no conversions at all:
DateTime date1=DateTime.Today.AddMonths(-1);
DateTime date2=DateTime.Today.AddMonths(1);
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con,
"select * from act_events where " +
" (#date1>=e_start and #date1 <= e_end) " +
" or (#date2>= e_start and #date2 <= e_end) "))
{
cmd.Parameters.AddWithValue("#date1", date1);
cmd.Parameters.AddWithValue("#date2", date2);
You don't need to specify the same date multiple times. If this query doesn't work it's either because the e_start and e_end fields are text fields or the WHERE clause is not what you expected.
You should also check whether #date2 is used correctly. Your query seems to look for records that cover #date1 or don't cover #date2. Is this correct?

Categories