I have 2 datetimepickers. In my select query i want to fetch records between these dates. datatype for date in database in varchar(MAX). For datetimepicker i have set custom format as dd-MM-yyyy. Here is my sql query
SqlDataAdapter da = new SqlDataAdapter("Select custname From tb_customer WHERE date >= '"+dtp_fromdate.Text+"' AND date <= '"+dtp_todate.Text+"'", con);
For eg: if my start date is 9-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and 11-06-2012
Incase if my start date is 10-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and not 11-06-2012
Please help
Use Convert or Cast T-SQL to convert VARCHAR value to Date or DateTime and also learn/use parameters instead of hard-coded SQL string.
The problem lies in lack of use of parameters. Using parameters will avoid any minsunderstanding between you and yuor database backend
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter();
string query = "Select custname From tb_customer WHERE date >= #from AND date <= #to"
da.SelectCommand = new SqlCommand(queryString, con);
da.SelectCommand.AddWithValue("#from" , dtp_fromdate.Value);
da.SelectCommand.AddWithValue("#to" , dtp_to.Value);
da.Fill(ds);
return ds;
}
Related
I have succeeded in getting all record of sales transaction for today on just clicking a button. Below is my codes
con.Open();
string query = "select Date Transactioncode, Productname, Total FROM Stock WHERE Date >= CAST(GETDATE() AS DATE) ORDER BY Date DESC";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
SDA.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
The problem I am having is how to get all sales transaction for the month or any month and year that i wish to search. I am using 2 comboBoxes to select month and year in order to get records from the SQLDatabase. Below the codes i had tried which kept producing error.
con.Open();
string query = "SELECT * FROM Stock WHERE Month(Date) = '"+comboMonth.Text+"' AND Year(Date) = '"+comboYear.Text+"'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
SDA.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
this is the error i got: Conversion failed when converting the varchar value 'January' to data type int"
kindly help please
I would do this on the SQL side, as there are functions there to render date in any form, which you can compare to. It might not make for the most efficient query.
Either rendering the date as a string would allow use of 'like' and an index (I always liked the ISO YYYY-MM-DD HH:MM:SS.ssssss), or indexing the function expression is also allowed now.
For just one year one month, you should calculate the first and last second/day of date-times and do a range scan on the date-time value, which is both more efficient and non-hash (ordered) index friendly. Some Date types are of day granularity, some are date-time. https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15 And of course the exact ends of days vary with Daylight Savings and the like, a real mess doing queries by shift on 3 shifts a day!
I am new to C#, and learning. I have a SQL Server database where I have table record that has a column dob of data type date. I am trying to insert into dob from my textbox which has a value of 19-08-17 with the following code
datebox.Text = "19-08-17";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", datebox.Text);
com.ExecuteNonQuery();
But I get this error
Conversion failed when converting date and/or time from character string.
How can I solve this?
When you pass a variable to a DateTime column as a parameter, you need to convert the text to a DateTime variable before passing it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].Connect ionString);
// Convert the textbox text to a DateTime variable
DateTime myDate = DateTime.ParseExact(datebox.Text, "dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture);
SqlCommand com = new SqlCommand(query, con);
string query= "insert into record (dob) values(#db)";
com.Parameters.AddWithValue("#db", myDate);
com.ExecuteNonQuery();
I am having an application that shows date and time in datagridview after exporting data from database to dataset.
Details : I have a column called Date that contains date and time in datetime2 format and when showing date, seconds don't show up.
con = new SqlConnection();
con.ConnectionString = my_connection_string;
con.Open();
adap = new SqlDataAdapter("SELECT Date,Object,ASDU,IOA,Alarm from Alarms_List",my_connection_string);
ds = new System.Data.DataSet();
adap.Fill(ds, "Alarms_List");
dataGridView1.DataSource = ds.Tables[0];
Example : Date table contains 15/07/2016 10:03:13
It's shown as : 15/07/2016 10:03
I have also tried CAST(Date AS DATETIME2) in the select statement but none of them works
You must set the "Format", sample like this :
dataGridView1.Columns[0].DefaultCellStyle.Format = "dd.MM.yyyy HH:mm:ss";
use :
select CONVERT(varchar(19), dateColumnName, 120) from tableName;
update:
You may also use the FORMAT function from SQL Server 2012 onwards as below:
select FORMAT(dateColumnName, date-format) from tableName;
ex
select FORMAT(GETDATE(), "dd/MM/yyyy hh:mm:ss");
I get this error when I compare to dates.
sql query command :
Select * from processTBL WHERE is=2016144 and date between '10/06/2016' and '15/06/2016'
that command work but when Fill Data to DateTabe I get converting error.
That's my c# method;
public DataGridView hesapOzeti(string command)
{
DataGridView gdview = new DataGridView();
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlCommand komut = new SqlCommand(command, connection);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Close();
gdview.DataSource = dt;
return gdview;
}
The Error:
A quick fix would be to send dates in an unambiguous format, so that your format is properly interpreted:
Select * from processTBL WHERE is=2016144 and date between '20160601' and '20160616'
The error comes from the fact that 15 is considered a month and thus the date is unparsable.
The correct way of doing it is to use a parameterized query:
command.Parameters.AddWithValue("#is", 2016144);
command.Parameters.AddWithValue("#FromDate", new DateTime(2016, 06, 10));
command.Parameters.AddWithValue("#ToDate", new DateTime(2016, 06, 15));
Your query becomes:
Select * from processTBL WHERE is = #is and date between #FromDate and #ToDate
Generally speaking, you should always try to use parameterized queries to avoid such errors and protect against SQL injection.
The date format for literals is dependant upon the locale (specifically the DATEFORMAT). The BOL page for datetime lists the locale and non-locale specific formats
https://msdn.microsoft.com/en-AU/library/ms187819.aspx
Ideally, you should use the ISO 8601 format - YYYY-MM-DDThh:mm:ss[.mmm] or
YYYYMMDD[ hh:mm:ss[.mmm]]
In your code, try date between '20160610' and '20160615'
I am currently using SqlDataAdapter to query a SQL database:
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
string cmd = #"select * from dbo.Table where errordate > '2015-05-29'";
myConnection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd, sqlConn);
da.Fill(dt);
The query is working fine but the only problem is that The date column does not include milliseconds. When I perform the same query with MS SQL server management studio, the milliseconds are there. Why wouldn't the milliseconds be present in C#?
Thanks
After reading the comments above I realized the issue was not with the SQL query but with the way I accessed the data from the DataTable. This did the trick:
DateTime date = (DateTime)dr[2];
string ds = date.ToString("MM/dd/yy HH:mm:ss.fff");
Cast your datetime variable to a string using
[YourDate].ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);