I am new in asp & sql server. I have a problem in sql query.
string obal ;
decimal _obalss = 0;
decimal obalss = 0;
sconnection c = new sconnection();
string cus_id = Session["cusid"].ToString();
DateTime maxdate = DateTime.Parse(fromdt.Text, new System.Globalization.CultureInfo("en-US"));
string mdate = maxdate.ToString();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
SqlDataReader dr = c.reader(query_sl);
if (dr.Read())
{
decimal.TryParse(dr["amount"].ToString(), out _obalss);
obalss = _obalss;
}
else
{
obalss = 0;
}
dr.Close();
dr.Dispose();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
maxdate is a date, you have to put it in single quotes. Even better you should use parameterized SQL queries otherwise you are vulnerable to SQL injection attacks. How about something like this:
string query_sl = "select sum(amount) as amount from sale where cusid = #CUSID and invdate < #MAXDATE group by cusid";
using(SqlCommand cmd = new SqlCommand(query_sl, c))
{
cmd.Parameters.Add(new SqlParameter("#CUSID", SqlDbType.Int)).Value = cus_id;
cmd.Parameters.Add(new SqlParameter("#MAXDATE", SqlDbType.DateTime)).Value = maxdate;
...
}
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < '" + maxdate + "' group by cusid";
Notice the single quotes around maxdate...
Related
I'm trying to get the date to store as a string in a table, but the date keeps converting to a negative 4 digit number which correlates with the date, and I can't for the life of me figure out where I've messed up. Note that I'm using a combo of C# and SQL Server
foreach(DataRow dr in dt.Rows)
{
int qty = 0;
string pname = "";
SqlCommand cmd3 = con.CreateCommand();
cmd3.CommandType = CommandType.Text;
cmd3.CommandText = "insert into order_item values('" + orderid.ToString() + "','" + dr["product"].ToString() + "'," +
"'" + dr["price"].ToString() + "','" + dr["qty"].ToString() + "','"+ dr["total"].ToString() + "')";
cmd3.ExecuteNonQuery();
qty = Convert.ToInt32(dr["qty"].ToString());
pname = dr["product"].ToString();
SqlCommand cmd6 = con.CreateCommand();
cmd6.CommandType = CommandType.Text;
cmd6.CommandText = "update stock set product_qty = product_qty - " + qty + " where product_name = '"+pname.ToString()+"'";
cmd6.ExecuteNonQuery();
// date keeps getting updated to negative 4 digit number which coordinates with the date. ex: 14-01-2020 is converting to -2007.
SqlCommand cmd7 = con.CreateCommand();
cmd7.CommandType = CommandType.Text;
**cmd7.CommandText = "update stock_over_time set product_qty = product_qty - " + qty + ", date_changed = " + date.ToString("dd-MM-yyyy") + "" +
" where product_name = '" + pname.ToString() + "'";**
cmd7.ExecuteNonQuery();
}
The immediate problem is that:
, date_changed = " + date.ToString("dd-MM-yyyy") + "
will become
, date_changed = 15-01-2020
which is: -2006, which is (because of how dates are stored) some time in July 1894.
A bad fix for this would be to add quotes, but this is: bad - it has a range of problems to do with internationalization (is 08-01 the first of August? the 8th of January?), SQL injection, etc.
The correct fix is to use parameters throughout. For example:
cmd7.CommandText = #"
update stock_over_time
set product_qty = product_qty - #qty,
date_changed = #date
where product_name = #pname";
This, however, requires you to add parameters with the values.
The simplest way to do this would be with Dapper:
string pname = ...
int qty = ...
DateTime date = ...
con.Execute(#"
update stock_over_time
set product_qty = product_qty - #qty,
date_changed = #date
where product_name = #pname",
new { pname, qty, date });
Note: all of your database access should be parameterized, either like the above, or using raw ADO.NET, or using tools like EF etc. Not just this one place; everywhere.
A date should not be stored as a string datatype, instead change date-changed to a datetime type (or even just a date, since the values stored have no "time" element).
Also, it is advisable to use a parameterized query to avoid SQL injection
string sql = #"update stock_over_time set product_qty = product_qty - #qty, date_changed = #date where product_name = #pname";
using (SqlConnection connection = new SqlConnection(connString)
{
connection.Open();
using (SqlCommand cmd= new SqlCommand(sql, connection))
{
cmd.Parameters.Add("#qty", SqlDbType.SqlInt32).value = qty;
cmd.Parameters.Add("#date", SqlDbType.SqlDateTime).value = date;
cmd.Parameters.Add("#pname", SqlDbType.Varchar, 50).value = pname;
cmd.ExecuteNonQuery();
}
}
I try to do it with expressions:
// QUERY
string query1 = "SELECT * "
+ "FROM Url_tabl "
+ "WHERE ID = (SELECT MAX(id) FROM Url_tabl)";
db.Execute(query1);
But the request does not work.
I tried for the test to check whether there is a connection to the database table.
To do this, use the expression:
string query1 = "delete from url_tabl";
This expression works.
To create a Recordset with the last entry from a database table, I tried several queries, but they do not work.
I get an error:
- "Cannot start a sample query."
string query1 = "select top 1 * "
+ "from url_tabl "
+ "order by id desc";
string query1 = "select max(id) "
+ "from url_tabl ";
string query1 = "select * "
+ "from url_tabl "
+ "where max(id)";
string query1 = "Select top 1 * "
+ "FROM Url_tabl "
+ "order by id desc";
"Recordset" I plan to use in this method.
public void TestDAOTransferToAccess()
{
try
{
DAO.DBEngine dbEngine = new DAO.DBEngine();
DAO.Database db = dbEngine.OpenDatabase(#"C:\db\db_test.accdb", false, false); // ++
// QUERY
string query1 = "SELECT * "
+ "FROM Url_tabl "
+ "WHERE ID = (SELECT MAX(id) FROM Url_tabl)";
db.Execute(query1); // Работает
DAO.Recordset rs = db.OpenRecordset("Url_tabl");
for (int i = 0; i < 10; i++)
{
rs.AddNew();
rs.Fields["status_url"].Value = "status_url_" + i;
rs.Fields["url"].Value = "status_url_" + i;
rs.Update();
}
rs.Close();
db.Close();
}
catch (Exception ex)
{
throw;
}
}
How to create a record with the latest record from a database table?
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();
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
I want to return the row ID from SQL Server through C#. Below is the code I am using:
const string sqlQuery = "SELECT ID " +
"FROM CleaningCycleTime " +
"WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE()) AND LotWorkOrder = #LotWorkOrder AND Process = #Process AND CleanType = #CleanType " +
"Group By ID " +
"Having (Min(ActualStartDayTime) IS NOT NULL AND Max(ActualFinishDayTime) IS NOT NULL)";
using (SqlCommand myCommand = new SqlCommand(sqlQuery, _myConnection))
{
try
{
myCommand.Parameters.AddWithValue("#LotWorkOrder", lstOpenCleans.SelectedItem.ToString());
myCommand.Parameters.AddWithValue("#Process", lstProcess.SelectedItem.ToString());
myCommand.Parameters.AddWithValue("#CleanType", lstProcess.SelectedItem.ToString());
_myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtID.Text = myReader["ID"].ToString();
}
_myConnection.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
_myConnection.Close();
}
}
Which generates
SELECT ID
FROM CleaningCycleTime
WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE())
AND LotWorkOrder = 'X90744'
AND Process = 'PRE BLEND'
AND CleanType = 'FULL'
GROUP BY
ID
HAVING
(Min(ActualStartDayTime) IS NOT NULL
AND Max(ActualFinishDayTime) IS NOT NULL)
When I run the generated query in SQL Server Management Studio, it returns a value. When I do this in C#, it gets as far as myReader.Read(), but never loops
I notice a couple of things:
1 - No quotes around your C# string where appropriate.
SQL:
AND LotWorkOrder = 'X90744'
AND Process = 'PRE BLEND'
AND CleanType = 'FULL'
vs
C#:
"AND LotWorkOrder = #LotWorkOrder AND Process = #Process AND CleanType = #CleanType "
2 - We do not see how your connection is defined. Why not wrap it in a using statement?
To be concise:
using (var cn = new SqlConnection("connection string"))
{
cn.Open();
using (var cmd = cn.CreateCommand())
{
// set the command text
const string sqlQuery = "SELECT ID " +
"FROM CleaningCycleTime " +
"WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE()) AND LotWorkOrder = '#LotWorkOrder' AND Process = '#Process' AND CleanType = '#CleanType' " +
"Group By ID " +
"Having (Min(ActualStartDayTime) IS NOT NULL AND Max(ActualFinishDayTime) IS NOT NULL)";
cmd.CommandText = sqlQuery;
// Add your paramters to the command object.
cmd.Parameters.AddWithValue("#LotWorkOrder", lstOpenCleans.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Process", lstProcess.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#CleanType", lstProcess.SelectedItem.ToString());
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
txtID.Text = myReader["ID"].ToString();
}
}
}
}
New sqlQuery:
const string sqlQuery = "SELECT ID " +
"FROM CleaningCycleTime " +
"WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE()) AND LotWorkOrder = '#LotWorkOrder' AND Process = '#Process' AND CleanType = '#CleanType' " +
"Group By ID " +
"Having (Min(ActualStartDayTime) IS NOT NULL AND Max(ActualFinishDayTime) IS NOT NULL)";