I have a table stored in SQL Server database. One of the fields of the table is of type DATETIME. I also have a ASP Calendar whose date is compared with the DATETIME filed of Database.
The problem is I don't want to compare the time. Only dates has to be compared. What is the SQL query for doing so.
This is what I used:
SqlCommand myCommand = new SqlCommand("
SELECT AUDIT.AUDIT_DETAILS, USERS.USER_NAME, AUDIT.DATE_TIME, IP
FROM USERS JOIN AUDIT ON (USERS.USER_ID = AUDIT.USER_ID)
WHERE USERS.USERS_NAME LIKE '%"+TextBox1.Text+"%' AND CONVERT(VARCHAR(10),AUDIT.DATE_TIME,110) like "+Calendar1.SelectedDate.Date+"'%'", conn);
I'm getting correct output in the SQL Server explorer but when run from browser through asp.net the query result is empty
Try modifying your query as below
SqlCommand myCommand = new SqlCommand("SELECT AUDIT.AUDIT_DETAILS, USERS.USER_NAME, AUDIT.DATE_TIME, IP
FROM USERS JOIN AUDIT ON (USERS.USER_ID = AUDIT.USER_ID)
WHERE USERS.USERS_NAME LIKE '%"+TextBox1.Text+"%' AND
CONVERT(VARCHAR(10),AUDIT.DATE_TIME,106) == CONVERT(VARCHAR(10),CAST('"+Calendar1.SelectedDate.Date+"' as DATETIME),106)", conn);
You can get only date from Datetime in SQL like this
CONVERT(DATE,GETDATE())
And after that you can compare to that value.
Related
I want to display data like this: image
I was fetching to fetch the details from from postgres tables with home controller like this:
public IActionResult AllTransactionsList(DateTime startDate, DateTime endDate)
{
var dataset = new DataSet();
using var connection = new NpgsqlConnection(connString);
connection.Open();
Console.WriteLine(startDate);
var query = String.Format(#"SELECT accounts.account,accounts.type,DATE(transactions.date),transactions.transactionid,transactions.amount,transactions.note FROM transactions FULL JOIN accounts ON transactions.accountid=accounts.accountid WHERE transactions.date BETWEEN '{0}' AND '{1}' ORDER BY transactions.date;", startDate, endDate);
string mainQuery = String.Format(#"SELECT sum(amount) FROM transactions INNER JOIN accounts ON transactions.accountid=accounts.accountid WHERE accounts.type='income' AND transactions.date BETWEEN '{0}' AND '{1}'", startDate,endDate);
using var mainCommand = new NpgsqlCommand(query, connection);
decimal mainResult = mainCommand.ExecuteNonQuery();
using (var command = new NpgsqlCommand(query, connection))
{
var adapter = new NpgsqlDataAdapter(command);
adapter.Fill(dataset);
}
return View(dataset);
}
but I need to also display the income/expense that is there at the bottom image
How to fetch data from two queries at the same time and put it in dataset?
i.e., I have two queries(query, mainResult). I will get rows from query and I will get decimal value from main result I need to return both of them in the view.
How can I achieve this? can anyone help me please?
Method 1.
You can splice two sql statements into one sentence.
Method 2.
Create a new dataset. After get mainQueryDataSet and queryDataSet, you can combine it.
In this particular case you can make the first query
SELECT
a.account,
a.type,
DATE(t.date),
t.transactionid,
t.amount,
t.note,
SUM(CASE WHEN a.type = 'income' THEN t.amount END) OVER(PARTITION BY a.account) as sumtrans
FROM
transactions t
INNER JOIN accounts ON t.accountid=a.accountid
WHERE
t.date BETWEEN #f AND #t
ORDER BY t.date
You'll need to make the command aware of the parameters:
adapter.SelectCommand.Parameters.AddWithValue("f", startDate);
adapter.SelectCommand.Parameters.AddWithValue("t", endDate);
See here for more information about passing datetimes to pg:
https://www.npgsql.org/doc/basic-usage.html
Never pass data to a database in the manner you have done so. Every SQL is a small program that gets compiled and run. By concatenating user-provided data into an SQL string you're giving your end users the ability to insert their own SQL ; you're basically giving them access to the database. Yes, it's pretty hard to hack a database when it's a date time variable but if you do it for dates this way, I'm sure you'll do it for strings and then you're staring down the barrel of the http://Bobby-tables.com gun. Even if you deem it safe, passing dates as strings to a database is problematic because they have to be parsed back to a date which means C# and PG have to align on a format.suppose C# string'd the date as "09/10/11" - what date is 09/10/11 anyway? 10th sept 2011? 9th Oct 2011? 11th oct 2009? 1909?
C# has dedicated DateTime datatypes, PG has dedicated DateTime datatypes and there is a mechanism for transmitting from c# to pg that doesn't trip via a formatted string; keep your data as a date
I made a programm, which shows a table from my database.
The Statement looks like that:
string sql = ("select CCase.RefNo AS Az, EventTemplate.EventCode AS
Vorgang from ikaros.CCase join ikaros.Event on CCase.ID =
Event.CCaseID join ikaros.EventTemplate on Event.EventTemplateID =
EventTemplate.ID where EventTemplate.EventCode='IRVB' and
Event.EventDate ='2014-07-03' order by CCase.RefNo ASC");
Now with
Event.EventDate='2014-07-03'
I get the table of that Date which is given in the SELECT Statement.
But I want give the user the opportunity to give a other Date in a Textbox.
The Textbox should change the Date in the Statement.
I looked here:
Try 1
Try 2
But it's not the same issue which I have.
If this is a duplicate and I was just to silly to find it, please tell me.
The added link in question shows your are using WPF So,
If your date is coming from TextBox then you should use TextBox.Text property to read date from user input like
var date = TextBox1.Text;
OR
If you used DatePicker then you can use DatePicker.SelectedDate.Value.Date property to read user input
var date = DatePicker1.SelectedDate.Value.Date;
And then pass this to sql query like
string sql = ("select ... where EventTemplate.EventCode='IRVB' and
Event.EventDate ='"+ date +"' order by CCase.RefNo ASC");
Note: Always use prepared statements (parameterized query) to prevent sql injection attack.
I m not sure that you are using ADO.NET but your paramterized query look like
string sql = ("select ... where EventTemplate.EventCode='IRVB' and
Event.EventDate = #date order by CCase.RefNo ASC");
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#date", date);
an error while storing date in DB (SQL server 2005) using C#
I am using,
DateTime mydate = DateTime.Now;
insert into mytablename (appdate) values('"+mydate.ToShortDateString()+"');
bt its showing error when I run the query
also tried,
mydate.ToShortDateString().ToString("dd-MMM-yyyy HH:mm:ss") in C# , still showing error in editor only.
How do I store 'date' in SQL Server 2005 using C# query
Use parameterized SQL, and set the value into the parameter:
string sql = "insert into tablename (appdate) values (#appdate)";
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#appdate", SqlDbType.DateTime).Value
= DateTime.Now;
int rowsInserted = command.ExecuteNonQuery();
// TODO: Validation of result (you'd expect it to be 1)
}
}
You should always use parameterized SQL when you have data to include in the request to the database. This avoids SQL injection attacks and data conversion issues, as well as keeping your code cleaner.
You should also consider whether you really want it to be the local date/time or the UTC date/time. For example, you might want to use DateTime.UtcNow instead.
Your query tries to insert a string in a DateTime field. And of course it doesn't work.
The correct way to insert is through a parametrized query like this
string insertSQL = "insert into mytablename (appdate) values(#dt)";
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#dt", mydate);
cmd.ExecuteNonQuery();
Here I assume that the connection is already initialized and opened
From my code, I call an SP using:
using (var cmd = new SqlCommand("sp_getnotes"))
{
cmd.Parameters.Add("#ndate", SqlDbType.SmallDateTime).Value
= Convert.ToDateTime(txtChosenDate.Text);
cmd.CommandType = commandType;
cmd.Connection = conn;
var dSet = new DataSet();
using (var adapter = new SqlDataAdapter { SelectCommand = cmd })
{
adapter.Fill(dSet, "ntable");
}
}
The Stored Procedure itself runs a simple query:
SELECT * FROM tblNotes WHERE DateAdded = #ndate
The problem is no records are returned! DateAdded is a smalldatetime column.
When I change the query to the following, it works:
SELECT * FROM tblNotes WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, DateAdded))) = #ndate
Why is this happening? This change affects the entire application and I'd like to find the root cause before getting into changing every single query... The only changes we made are to use parameterized queries and upgrade from SQL Server 2005 to 2008.
TIA.
smalldatetime has a time portion which needs to match as well.
Use this:
SELECT *
FROM tblNotes
WHERE dateAdded >= CAST(#ndate AS DATE)
AND dateAdded < DATEADD(day, 1, CAST(#ndate AS DATE))
SQL Server 2008 and above also let you use this:
SELECT *
FROM tblNotes
WHERE CAST(dateAdded AS DATE) = CAST(#ndate AS DATE)
efficiently, with the transformation to a range performed by the optimizer.
SQL Server 2008 now has a DATE data type, which doesn't keep the time porttion like SMALLDATETIME does. If you can't change the data type of the column, then you'll have to truncate when doing the compare, or simply cast to DATE:
SELECT *
FROM tblNotes
WHERE cast(dateAdded as date) = #ndate
I don't know SQL Server but from Oracle experience I'd suspect you're comparing a date time with a date, eg 01/01/2012 01:01:01 against 01/01/2012.
I have a strange problem...I have a MySql db with some columns and one of the column is date_purchased which is of type date_time.
I am using C# and made a DatetimePicker and user selects a date.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
varDate = dateTimePicker1.Value;
}
Now the problem is I have to compare the two datetimes (one from the database and one from the User) and I should display the records that are less than the date selected by the user(varDate).
select * from orders where date_purchased < = '" + varDate + "'";
I am executing this query but i am getting an exception
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '12/25/2011 8:01:31 PM'' at line 1
I wrote the connection string and all and I am struck at the query.
Any Help will be much appreciated...
Thanks,
Subash
You have not given any details on what you are using to run the select query; however, if you are using the connector provided by Mysql (Connector/Net) then you should be using parameters. Which would look something like this:
String sql = "select * from orders where date_purchased < #DatePurchased";
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
adapter.SelectCommand.Parameters.Add("DatePurchased", MySqlType.DateTime).Value = varDate;
adapter.Fill(dataSet);
Using parameters will ensure the values are converted and will also prevent SQL Injections
Try something like where DBdatetime < "'" + vardate + "'"
One word of caution, check the formats of the two dates. I had a problem in a previous app where the DB had seconds and milliseconds, whereas the app provided just a data and set the time to 00:00. This resulted in records for the current date not showing in the result set. Thus, I had to add 23:59 to the date to get all the records for the current day.
You can retrieve the values between the two data using the following MySQL Query
SELECT * FROM table_name WHERE dbvalue < varData