The DayDate column in the database is of type DateTime & I'm passing a string formulated using a DateTimePicker in a form. The reader.HasRows always returns false!! I don't know what I'm doing wrong. Any help would be appreciated. The code that I used is below.
if (!this.con.IsConnected())
{
this.con.Connect();
}
this.cmd = new OleDbCommand("SELECT DayNo FROM [Calendar] WHERE DayDate = " + date + "", this.con.conObj());
this.reader = cmd.ExecuteReader();
this.reader.Read();
int dayNo;
if (this.reader.HasRows)
{
dayNo = int.Parse(reader[0].ToString());
}
else
{
throw new InfoException("The system could not locate the date in the system");
}
The problem is your comparing a Date value to a DateTime so in essence you could possibly be comparing values like this:
DayDate = "2011-12-18 14:22:54"
Date = "2011-12-18 00:00:00"
You need to truncate the time part from your DB dates, try something like this:
"SELECT DayNo FROM [Calendar] WHERE dateadd(dd, 0, datediff(dd, 0, DayDate)) = " + date
Or if using SQL Server 2008 you can do:
"SELECT DayNo FROM [Calendar] WHERE cast(DayDate As Date) = " + date
Related
I have a chart in asp.net web form page. i want to fill it with a custom query created by joining two variables from the same sql table.
Here is the code (query):
String year2 = Convert.ToString(dropDownStartYear.Text);
String month2 = Convert.ToString(dropDownMonth2.Text);
String day2 = Convert.ToString(dropDownDay2.Text);
String hour2 = Convert.ToString(dropDownHour2.Text);
String minute2 = Convert.ToString(dropDownMinute2.Text);
String year3 = Convert.ToString(dropdownYear3.Text);
String month3 = Convert.ToString(dropDownMonth3.Text);
String day3 = Convert.ToString(dropDownDay3.Text);
String hour3 = Convert.ToString(dropDownHour3.Text);
String minute3 = Convert.ToString(dropDownMinute3.Text);
SqlConnection connection = ConnectionManager.getConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT id, temperature, year, month, day , hour, minu from datab where year = #year and month=#month and day=#day and hour=#hour and minu=#minute ; ";
cmd.Parameters.AddWithValue("#year", year2);
cmd.Parameters.AddWithValue("#month", month2);
cmd.Parameters.AddWithValue("#day", day2);
cmd.Parameters.AddWithValue("#hour", hour2);
cmd.Parameters.AddWithValue("#minute", minute2);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
}
where i want to select a start date and time (year, month, day, hour, minute) from a table in sql server and also select an end date with same variables.
then i want to draw the "temperature" that varies from the start time to the end time.
any help there?
Try this query, building DateTime objects from the date parts in the input and stored in your table. That should make it easier to compare and restrict your return values by the selected input values:
cmd.CommandText = #"select [id], [temperature], [year], [month], [day], [hour], [minu]
from datab
where DATETIMEFROMPARTS([year], [month], [day], [hour], [minu], 0, 0)
between DATETIMEFROMPARTS(#year2, #month2, #day2, #hour2, #minute2, 0, 0)
and DATETIMEFROMPARTS(#year3, #month3, #day3, #hour3, #minute3, 0, 0)";
// beginning of date range
cmd.Parameters.AddWithValue("#year2", year2);
cmd.Parameters.AddWithValue("#month2", month2);
cmd.Parameters.AddWithValue("#day2", day2);
cmd.Parameters.AddWithValue("#hour2", hour2);
cmd.Parameters.AddWithValue("#minute2", minute2);
// end of date range
cmd.Parameters.AddWithValue("#year3", year3);
cmd.Parameters.AddWithValue("#month3", month3);
cmd.Parameters.AddWithValue("#day3", day3);
cmd.Parameters.AddWithValue("#hour3", hour3);
cmd.Parameters.AddWithValue("#minute3", minute3);
Try this query...
cmd.CommandText = "SELECT id, temperature, year, month, day , hour, minu from datab
where CONVERT ( datetime , cast(year as varchar)+'-'+cast(month as varchar)+'-'+cast(day as varchar)+' '+cast(hour as varchar)+':'+cast(minute as varchar)+':'+'00' , 20) >= CONVERT ( datetime , #yearfrom+'-'+#monthFrom+'-'+#dayFrom+' '+#hourFrom+':'+#minuteFrom+':'+'00' , 20)
and CONVERT ( datetime , cast(year as varchar)+'-'+cast(month as varchar)+'-'+cast(day as varchar)+' '+cast(hour as varchar)+':'+cast(minute as varchar)+':'+'00' , 20) <= CONVERT ( datetime , #yearTo+'-'+#monthTo+'-'+#dayTo+' '+#hourTo+':'+#minuteTo+':'+'00' , 20);";
i have a web service in which training number is assigning as per my database
there is a line
dates + "1"; this lines add 1 in date
like 27012017 will become 270120171
then i convert this into int64
newid = Convert.ToInt64(dates);
but now i want to add trainer id in this
so i updated my line with this
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
the error is coming input string is not in correct format,
i know this is because of the addition of +"-"+
but i want to store the data in this format only
and my whole portion look like
DateTime dt = DateTime.Now;
string dates = dt.ToString();
dates = dates.Replace("-", "");
dates = dates.Substring(0, 8);
SqlCommand cmdbill = new SqlCommand("select top 1 * from listmybill where bill_id like #trid order by bill_id desc", con);
con.Open();
cmdbill.Parameters.AddWithValue("#trid", "%" + dates + "%");
SqlDataReader dr = cmdbill.ExecuteReader();
while (dr.Read())
{
value = dr["bill_id"].ToString();
}
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdbill);
DataTable dat = new DataTable();
da.Fill(dat);
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
else
{
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
}
con.Close();
what should i do here,
i want to enter the data like 001-270120171
and if i convert toInt64 into string,
there can be problem when a row found in the table
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
what i need to do now?
i want to store this into my database
I hardly think you will be doing mathematical calculations on this training number string. I suggest that you convert the int in your database into a varchar using alter statement. Then you you will be able to store the training number in whichever format you like.
You can change new id to string and do the following
if (dat.Rows.Count > 0)
{
newid = Convert.ToString(Convert.ToInt64(value)+1);
}
else
{
newid="00"+trainerid +"-"+ dates + "1";
}
I wanted to display all rows and columns in my DB between specific dates on an aspx web. However, dates are not recorded in date or date time format. And it seems it is not possible to convert them to date format. I try to do this like this;
public DataTable DisplayRecord()
{
var reqID = Request.QueryString["MyId"].ToString();
//Date parsing
String[] ids = reqID.Split('-');
String date1 = ids[0];
String date2 = ids[1];
String provider = ids[2];
SqlDataAdapter Adp = new SqlDataAdapter("SELECT * FROM flightLogs WHERE depDate_depTime=CONVERT(date,depDate_depTime,104) AND depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104)", connection);
/*SqlDataAdapter Adp = new SqlDataAdapter("SELECT F.PNR, C.amount, F.provider, F.depDate_depTime FROM flightLogs F INNER JOIN companyLogs C ON F.PNR = C.PNR"+
" WHERE F.depDate_depTime=CONVERT(date,F.depDate_depTime,104) AND F.depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104) AND F.provider='" + provider + "' ORDER BY F.depDate_depTime ASC", connection);*/
DataTable Dt = new DataTable();
Adp.Fill(Dt);
FlightMonitor.DataSource = Dt;
FlightMonitor.DataBind();
return Dt;
}
But i get this error;
"Conversion failed when converting date and/or time from character string."
Also data in my DB is shown like this;
origin destination deptDate_depTime PNR flightno provider
KBP AMS 18.09.2015 - 17:35:00 5RQZ43 PS712 Amadeus
ATH FRA 10.07.2015 - 12:30:00 ZFY8XW PS716 PGS
it is a bad idea to store datetime values in varchar columns as you can see.
if you need a specific format, then you should convert it while you are about to display that value to the users.
but to make things working for now, you can change your where clause from this:
depDate_depTime=CONVERT(date,depDate_depTime,104)
to this:
depDate_depTime = convert(datetime, left(depDate_depTime, 10) + ' ' + right(depDate_depTime, 8), 104)
I am attempting to use "%" in order to search for a range of dates. In the table the dates are of the format "03/01/2015" and I am trying to return data for all dates of a specific month (03/2015 for example).
I am creating two strings of the format...
String datePrev1 = monthLast + "%";
String datePrev2 = "%" + yearLast;
Where datePrev1 == "03%" and datePrev2 == "%2015" which I have confirmed to be generating correctly.
My SQL search method is...
SqlCommand selectCommand = new SqlCommand("SELECT project, prevWeekHours FROM submissionsHours WHERE (WWID = '" + ID + "' AND (datePrevWeek LIKE '" + datePrev1 + "' AND datePrevWeek LIKE '" + datePrev2 + "'))", Conn1);
Conn1.Open();
SqlDataReader reader = selectCommand.ExecuteReader();
int totalTime = 0;
while (reader.Read() == true)
{
project.Add(reader[0].ToString());
projTime.Add(Convert.ToInt32(reader[1]));
totalTime += Convert.ToInt32(reader[1]);
}
Conn1.Close();
int index = project.Count; //total amount of projects
testLabel.Text = index.ToString() + "..." + datePrev1+datePrev2;
The testLabel.Text I have for troubleshooting is returning 0 for the index indicating there were no matches for this string when there are certainly entries in the table that should match it.
Any ideas on what I am doing wrong?
I have attempted querying like...
... WHERE datePrevWeek LIKE '03/__/2015';
... WHERE datePrevWeek LIKE '03____2015';
To no success... Thanks.
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND (YEAR(datePrevWeek)*100)+MONTH(datePrevWeek) = #YEARMONTH
#YEARMONTH should be of format 201503 representing march 2015.
Using parameters will avoid sql injection.
When datePrevWeek is varchar
SELECT project, prevWeekHours
FROM submissionsHours
WHERE WWID = #ID
AND right(datePrevWeek,7) = #YEARMONTH_STR
#YEARMONTH_STR is of format '01/2015'
Once you store dates in the format '2015-03-13',...
Plan A: WHERE dt LIKE '2015%'
Plan B (This is more efficient, given a suitable index):
WHERE dt >= CONCAT('2015', '-01-01')
AND dt < CONCAT('2015', '-01-01') + INTERVAL 1 YEAR
(I'm assuming '2015' is filled in by the code.)
Try Below:
Declare #Dat Date
set #Dat = '03/01/2015'
SELECT CAST(MONTH(#Dat) AS VARCHAR(2)) + '/' + CAST(YEAR(#Dat) AS VARCHAR(4)) AS [DD/YYYY]
I have a talent table holding all my users with a column holding their birthdays. what would be the best way Talent within a specified age range. Here's what I have, but is seems to be off by a couple days. is there a better way?
// BUILD SQL FROM FORM DATA
sqlString += "SELECT * from Talent";
if (minAge != 0 || maxAge != 120)
{
// The age criteria has been change, filter by age.
// select all talents that have birthdays between the following 2 dates.
DateTime startDate = (DateTime.Now - new TimeSpan((maxAge * 365), 0, 0, 0)); // maxAge * 365 = totalDays
DateTime endDate = (DateTime.Now - new TimeSpan((minAge * 365), 0, 0, 0));
sqlString += " WHERE Birthdate BETWEEN '" + startDate.ToString() + "' AND '" + endDate.ToString() + "'";
}
Assuming you're using SQL Server...
using (var connection = new SqlConnection(connString))
using (var command = connection.CreateCommand()) {
string tsql = #"
select *
from Talent
where DATEDIFF(YEAR, BirthDay, GETDATE()) BETWEEN #minAge AND #maxAge";
command.CommandText = tsql;
command.CommandType = CommandType.Text;
int minAge = 1;
int maxAge = 120;
SqlParameter minAgeParam = command.CreateParameter();
minAgeParam.Direction = ParameterDirection.Input;
minAgeParam.DbType = SqlDbType.TinyInt;
minAgeParam.ParameterName = "#minAge";
minAgeParam.Value = minAge;
SqlParameter maxAgeParam = command.CreateParameter();
maxAgeParam.Direction = ParameterDirection.Input;
maxAgeParam.DbType = SqlDbType.TinyInt;
maxAgeParam.ParameterName = "#maxAge";
maxAgeParam.Value = maxAge;
// Just unsure here whether I must add the parameters to the command,
// or if they are already part of it since I used the
// SqlCommand.CreateParameter() method.
// Been too long since I haven't done any ADO.NET
command.Parameters.Add(minAgeParam);
command.Parameters.Add(maxAgeParam);
connection.Open();
SqlDataReader reader = null;
try {
reader = command.ExecuteReader();
// Process your records here...
} finally {
connection.Close()
command.Dispose();
connection.Dispose();
if (reader != null) {
reader.Dispose();
}
}
}
Where #minAge and #maxAge are your age parameters.
You may also tell the DATEDIFF TSQL function to consider the difference in days, in month, in hours, in minutes, in seconds, etc. Hence, you will have to convert your parameters value accordingly.
Personally, I've found using startDate.ToString("yy-MM-dd 00:00:00.000") and endDate.ToString("yy-MM-dd 23:59:59.000") works best (note the ,000 on the end date range. For some reason, in my experience, sql is off (probably due to some kind of rounding error) when it comes to ranges.
As an aside, you can use static methods from the TimeSpan object for time calculations. e.g. TimeSpan.FromDays(...)
The problem might be related to DateTime.Now, which considers time as well as date. Try replacing it with a DateTime.Today.
Why don't you use DateTime.AddYears method.
DateTime startDate = DateTime.Now.AddYears(-maxAge);
insated of
DateTime startDate = (DateTime.Now - new TimeSpan((maxAge * 365), 0, 0, 0));
Another thing is: Please don't use + operator between strings to build a sql query, use StringBuilder instead.
For what it's worth - your original solution is off by a few days because it is using 365 instead of accounting for leap years.