I have a table named RETAILTRANSACTIONTABLE which has a column named BUSINESSDATE which has date in format(yyyy-mm-dd) 2015-05-22.
I want to comapre this date with batch.StartDateTime of format (dd-mm-yyyy hh:mm:ss) 05-10-2015 12:09:03.
var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
" FROM ax.RETAILTRANSACTIONTABLE where "+
"(CONVERT(VARCHAR(10),BUSINESSDATE,105) >= '" + date
+ "') and DISCAMOUNT > 0
Using the above query gives me all the values of the column I just want the count of values greater than or equal to batch date
You can use :
var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
" FROM ax.RETAILTRANSACTIONTABLE "+
" WHERE BUSINESSDATE >= CONVERT(DATE, '" + date + "', 105)
and DISCAMOUNT > 0 "
And, bonus, this use index on BUSINESSDATE if an index exist.
or better as #FelixPamittan said, use a prepared statement with binding :
var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
" FROM ax.RETAILTRANSACTIONTABLE "+
" WHERE BUSINESSDATE >= :theDate
and DISCAMOUNT > 0 "
I think this will do the trick for you
var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT " +
" FROM ax.RETAILTRANSACTIONTABLE WHERE" +
"BUSINESSDATE > = (CONVERT(VARCHAR, " + #dateParam + " ,105) >= '" +
+ "') and DISCAMOUNT > 0
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("dateParam", date.ToString("yyyy/mm/dd"));
With the help of above answers I modified it and finally got the solution
var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToString("yyyy-MM-dd");
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
" FROM ax.RETAILTRANSACTIONTABLE where "+
"BUSINESSDATE >= '" + date + "'" +
" and DISCAMOUNT > 0
Related
string TJOBCODE1 = ddlJobCode.SelectedItem.Value;
string abc = ddlJobCode.SelectedItem.ToString();
string TJob_Name = abc.Substring(0, abc.IndexOf('['));
string TRo_Name = abc.Substring(abc.LastIndexOf('[') + 1);
TRo_Name = TRo_Name.Replace("]", "");
string TJOBCODE = TJOBCODE1;
SqlCommand fsql = new SqlCommand("SELECT COUNT(*) AS REC FROM [MTS_TV_RO_TC_FINAL] where JOB_CODE='" + TJOBCODE + "' AND AGENCY_CODE in( select agency_code FROM " + tmptvrlbktbl + ")", Global.con1);
SqlDataAdapter Fda1 = new SqlDataAdapter(fsql);
DataTable Fdt1 = new DataTable();
Fda1.Fill(Fdt1);
int DD = Convert.ToInt32(Fdt1.Rows[0].ItemArray.GetValue(0).ToString());
if (DD == 0)
{
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],'" + COMP_FROM + "','" + COMP_TO + "',GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
SqlCommand cmd1 = new SqlCommand(INSQURY, Global.con1);
cmd1.ExecuteNonQuery();
Alert.show1("Data Saved Successfully", this);
}
else
{
Alert.show1("Data Already Saved", this);
return;
}
The code was perfectly fine, there was an issue with the excel sheet. i changed the query to parametrized and changed the excel sheet as well and it worked.
Change insQury to
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],COMP_FROM, COMP_TO,GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
If COMP_FROM and COMP_TO are dates already you don't need to surround them with single quotation marks.
I am trying to display available Tutors and Rooms at a certain date at a certain time.
I have 3 tables Lesson table, Room Table and Tutor Table. I am trying the code below
string sqlFormattedDate = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss.fff");
db.Cmd = db.Conn.CreateCommand();
db.Cmd.CommandText = "SELECT RoomNumber FROM RoomTBL WHERE RoomNumber NOT IN (
SELECT RoomNumber FROM LessonsTBL Where PupilID = " + 1 + " AND
StartDate = '" + sqlFormattedDate + "')";
db.Cmd.ExecuteNonQuery();
while (db.Rdr.Read())
{
listBox1.Items.Add(db.Rdr);
}
db.Rdr.Close();
I keep getting a System.NullReferenceException on the db.Rdr, but that works completely fine for all other queries.
I have read around other questions and I came up with this solution which doesn't work.
Try adding another condition to make sure that the reader has rows available to read:
string sqlFormattedDate = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss.fff");
db.Cmd = db.Conn.CreateCommand();
db.Cmd.CommandText = "SELECT RoomNumber FROM RoomTBL WHERE RoomNumber NOT IN (SELECT RoomNumber FROM LessonsTBL Where PupilID = " + 1 + " AND StartDate = '" + sqlFormattedDate + "')";
db.Cmd.ExecuteNonQuery();
if (db.Rdr.HasRows)
{
while (db.Rdr.Read())
{
listBox1.Items.Add(db.Rdr);
}
}
db.Rdr.Close();
ExecuteNonQuery returns the query execution status, to be specific returns The number of rows affected (source : System.Data.Common.DbCommand), try using ExecuteReader which will remove your NullReferenceException
string sqlFormattedDate = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss.fff");
db.Cmd = db.Conn.CreateCommand();
db.Cmd.CommandText = "SELECT RoomNumber FROM RoomTBL WHERE RoomNumber NOT IN (SELECT RoomNumber FROM LessonsTBL Where PupilID = " + 1 + " AND StartDate = '" + sqlFormattedDate + "')";
//db.Cmd.ExecuteNonQuery();
db.Rdr = cmd.ExecuteReader()
if (db.Rdr.HasRows)
{
while (db.Rdr.Read())
{
listBox1.Items.Add(db.Rdr);
}
}
db.Rdr.Close();
The value of dt.Rows.Count always equals 1, and the value of dt.Rows[0][0] and dt.Rows[0][ 1] is empty string when I query sqlStr of no records.
But I execute sqlStr in database. It's null. Here is the database screenshot
I don't know why it is.
string sqlStr = "select SUM(userIncome),SUM(userSpend) from tb_billlist where userPhone = '" + userPhone + "' and " +
"billTime between '" + beginDate + "' and '" + endDate + "'";
//execute sql
DataTable dt = new DataTable();
dt = MysqlHelper.ExecuteDataTable(sqlStr);
if (dt.Rows.Count > 0)
{
userBillInfo.userAllIncome = (float.Parse)(dt.Rows[0][0].ToString());
userBillInfo.userAllSpend = (float.Parse)(dt.Rows[0][1].ToString());
}
else
{
userBillInfo.userAllIncome = 0;
userBillInfo.userAllSpend = 0;
}
To achieve this goal you can change your query, and if case of 'sum of nulls', the return value is 0:
string sqlStr = "select COALESCE(SUM(userIncome), 0), COALESCE(SUM(userSpend), 0) from tb_billlist where userPhone = '" + userPhone + "' and " +
"billTime between '" + beginDate + "' and '" + endDate + "'";
//execute sql
...
Thus, you would have 0 as the return value for the fields.
I am using ms access as database that contains field identified as (short date)
i inserted time to that field from datetimepicker in C# using the following query:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "','"+dateTimePicker1.Text+"')";
and everything is ok. But when i am trying to compare the date in the database with date from another datetimpicker it doesnot work. This is the query of comparsion:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= " + dateTimePicker1.Value.Date.ToShortTimeString() + " "
"and category_in.dates<= " + dateTimePicker2.Value.Date.ToShortTimeString() + "";
when i use dateTimePicker.value.Date it gives me the following error
Syntax error (missing operator) in query expression
'category_in.dates>= 16/08/2015 12:00:00 ص and category_in.dates<=
20/08/2015 12:00:00 ص
but when i add dateTimePicker.value.Date.ToShortTimeString no results returned although there are some data between these dates
do i have to change the insertion method?
I'm surprised that all three answers (so far) have suggested that you continue using dynamic SQL and fiddle with your string-formatted dates and delimiters until you get something that works.
That's just dumb.
The DateTimePicker control returns a System.DateTime value so you should just use that as part of a parameterized query, something like this:
using (var conn = new OdbcConnection(
#"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
#"Dbq=C:\Users\Public\Database1.accdb"))
using (var cmd = new OdbcCommand("INSERT INTO MyTable (DateTimeField) VALUES (?)", conn))
{
conn.Open();
cmd.Parameters.Add("?", OdbcType.DateTime).Value = dateTimePicker1.Value.Date;
cmd.ExecuteNonQuery();
}
I think your code should use the # delimiter for date expressions in Access:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "',#" + DateTime.Parse(dateTimePicker1.Text).ToString("yyyy'/'MM'/'dd") + "#)";
and:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates >= #" + dateTimePicker1.Value.Date.ToString("yyyy'/'MM'/'dd") + "# "
"and category_in.dates <= #" + dateTimePicker2.Value.Date.ToString("yyyy'/'MM'/'dd") + "#";
Try changing your query to this:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= #" + dateTimePicker1.Value.ToShortDateString() + "# "
"and category_in.dates<= #" + dateTimePicker2.Value.ToShortDateString() + "#";
The issue is your dates are strings. Add Single quotes before and after your datetime values. Like this...
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= '" + dateTimePicker1.Value.Date.ToShortTimeString() + "' "
"and category_in.dates<= '" + dateTimePicker2.Value.Date.ToShortTimeString() + "'";
This will allow the query engine to implicitly convert the strings to datetimes.
I have to take 2 values from DateTimePicker and then compare their values with that in database.
Code:
string dt_start = dateTimePicker1.Value.ToShortDateString();
string dt_end = dateTimePicker2.Value.ToShortDateString();
string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between " + dt_start + " and " + dt_end + " ";
It is not showing any error, but I am not getting output values.
Access uses # for dates. This should work:
string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between #" + dt_start + "# and #" + dt_end + "#";
try the following select statement:
string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between '" + dt_start + "' and '" + dt_end + "' ";