Can't convert from string to smalldatetime value - c#

This is my statement that throws Exception saying
Can't convert from string to smalldatetime value
How do I fix it or write the correct statement?
da = new SqlDataAdapter("SELECT name,[build-id],exitTime,enterTime,tagType FROM Employees,GateLogging WHERE GateLogging.tagType='Employee' AND enterTime=DATEDIFF(minute,GateLogging.enterTime,GETDATE())>10", MyConn);

In the WHERE clause, remove the single quotes around the DATEDIFF(minute,GateLogging.enterTime,GETDATE())>10 statement.
EDIT
You're also comparing a datetime field against what I'd call a boolean. Remove the enterTime=. Your statement should look like this:
da = new SqlDataAdapter("SELECT name,[build-id],exitTime,enterTime,tagType FROM Employees,GateLogging WHERE GateLogging.tagType='Employee' AND DATEDIFF(minute,GateLogging.enterTime,GETDATE())>10", MyConn);
EDIT 2
Your table definition is as follows:
tagID bigint
enterTime nchar(10)
exitTime nchar(10)
date nchar(10)
Of course, enterTime can not be used in DATEDIFF, as it is not a DATETIME.
Question: Why are you storing dates and times as NCHAR(10) instead of DATETIME? That's not good style!
Solution 1: Change enterTime and exitTime to DATETIME and you're fine.
Solution 2: Change your statement, so that you convert enterTime to a valid DATETIME. I assume that enterTime only contains the time of day, so you'd have to mix in the date part before converting.
EDIT 3
Assuming that date stores the day in format yyyymmdd and enterTime stores the time in format hh:mm:ss, you'll be able assemble a DATETIME:
CONVERT(DATETIME, SUBSTRING(date, 1, 4) + '-' + SUBSTRING(date, 5, 2) + '-' + SUBSTRING(date, 7,2) + ' ' + entryTime, 102)
So your statement from above would look like:
da = new SqlDataAdapter(
"SELECT name,[build-id],exitTime,enterTime,tagType
FROM Employees,GateLogging
WHERE GateLogging.tagType='Employee' AND
DATEDIFF(minute,CONVERT(DATETIME, SUBSTRING(date, 1, 4) + '-' + SUBSTRING(date, 5, 2) + '-' + SUBSTRING(date, 7,2) + ' ' + entryTime, 102),GETDATE())>10", MyConn);
In case the date/time format stored in the fields of your database are different, you'll have to adjust the SUBSTRING statements within the CONVERT() accordingly.

First thing you were putting DATEDIFF stuff in quotes (') and comparing it with enterTime which I suspect is smalldatetime type so you got the error. Correct SQL will be:
SELECT name,[build-id],exitTime,enterTime,tagType
FROM Employees,
GateLogging
WHERE
GateLogging.tagType='Employee'
AND
enterTime = DATEDIFF(minute,GateLogging.enterTime,GETDATE())
As for your >10 I think you should not compare it with enterTime but use this instead:
SELECT name,[build-id],exitTime,enterTime,tagType
FROM Employees,
GateLogging
WHERE
GateLogging.tagType='Employee'
AND
DATEDIFF(minute,GateLogging.enterTime,GETDATE()) >10

I'd also not for you that you're not using ANSI style join syntax - this might cause you a few problems in later life.

Related

Datetime in SQL Server and C#

I have this simple query
insert into my_table(date) values(getdate())
The result is 2017-01-05 12:41:37.273.
I want when I do
select *
from my_table
from my Windows Forms application to set the label1.text = 5 Thu 12:41
2017-01-05 12:41:37.273 ----> 5 Thu 12:41
How can I achieve that with C# code ?
Assuming that you read the data from SQL Server into your C# application I'm pretty sure, that a column of sql type DATETIME will be mapped to a C# type DateTime.
What you need is the textual format of this:
DateTime d = DateTime.Now;
MessageBox.Show(d.ToString("d ddd HH:mm"));
You can parse string to DateTime and wrtie your own format.
DateTime myDateTime = DateTime.Parse("2017-01-05 12:41:37");
string formatedDateTime = myDateTime.ToString("dd-mm-yyyy");
From SQL you can you the below format to get your expected result:
SELECT CAST(DATEPART(D, GETDATE()) AS VARCHAR(2)) + ' ' +
LEFT(DATENAME(WEEKDAY, GETDATE()), 3) + ' ' +
LEFT(CONVERT(VARCHAR(8), GETDATE(), 108), 5)
-- Output: 5 Thu 05:22

How to convert string to datetime in sql server

I want to count total time in hh:mm:ss format. and I have minutes in int like (465).
I made:
CONVERT(varchar, CONVERT(datetime, cast(cast(TotalMin/60 as int) as nvarchar(50)) + ' : ' + cast(TotalMin%60 as nvarchar(50))),108) AS TotalMin
but it shows below error. Not in SQL Server but when I run code in c#:
Conversion failed when converting date and/or time from character
string.
You can use this code to get the string in SQL Server. It will convert hours and minutes and add 00 for seconds as you don't have them (you're using integer value for minutes):
declare #min int = 465
select right('0' + cast(#min/60 as varchar(2)),2)
+ ':'
+ right('0' + cast((#min - (#min/60)*60) as varchar(2)),2)
+ ':00'
It will work for up to 5999 minutes (99 hours and 59 minutes).
If you need a Unicode version:
declare #min int = 465
select right(N'0' + cast(#min/60 as nvarchar(2)),2)
+ N':'
+ right(N'0' + cast((#min - (#min/60)*60) as nvarchar(2)),2)
+ N':00'
Try this:
TimeSpan t = TimeSpan.FromMinutes( TotalMin);
and see this for more
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
This will help you
You want to multiply out to milliseconds as the fractional part is discarded.
SELECT DATEADD(ms, 121.25 * 1000, 0)
If you want it without the date portion you can use CONVERT, with style 114
SELECT CONVERT(VARCHAR, DATEADD(ms, 121.25 * 1000, 0), 114)

Conversion of a Varchar Datatype to a datetime resultant in an out of range

I have problem. I can' identify my mistake...
int dt = Convert.ToInt32(Items.Rows[T1]["F14"].ToString().Trim());
int mn = Convert.ToInt32(Items.Rows[T1]["F15"].ToString().Trim());
int yr = Convert.ToInt32(Items.Rows[T1]["F16"].ToString().Trim());
string DtString = mn.ToString().Trim() + "/" + dt.ToString().Trim() + "/" + yr.ToString().Trim();
DateTime RegExp = Convert.ToDateTime(DtString);
exp_date is datetime field in sqlserver.
string MyDtQry = "UPDATE MyTable SET exp_date='" + RegExp + "' where MyTable.id_no='" + AlmIDNo + "'";
But I'am getting the error:
Conversion of a Varchar Datatype to a datetime resultant in an out of range
Well, I would approach the task very differently:
After getting the day, month and year as integers I definitely wouldn't stick them back together and parse them. Just use:
// Note the meaningful variable names here, btw...
DateTime date = new DateTime(year, month, day);
When updating the database, I wouldn't put the value directly into the SQL statement. Use a parameterized SQL statement instead, and set the parameter to date. That way you don't need to worry about the database expecting a different date format to the one you provide. In general, you should always use parameterized SQL rather than embedding the values directly into the SQL - as well as helping with this kind of situation, it avoids SQL injection attacks.
Now, after doing all of that, if you're still getting an error, you should check what actual data you're trying to insert. Maybe the data in Items really is out of range for SQL Server.
It is hard to see exactly since you don't show any of your inputs; however, the following is clearly dangerous:
DateTime RegExp = Convert.ToDateTime(DtString);
string MyDtQry = "UPDATE MyTable SET exp_date='" + RegExp + "' where MyTable.id_no='" + AlmIDNo + "'";
Even if we gloss over the fact that you should be using parameters (you really should), you would need to format this date in the way that SQL server expects - which could be very different to the local format.
However; don't bother formatting it! Use a parameter for this, and it'll go away. This doesn't need to be hard - for example with dapper:
DateTime RegExp = new DateTime(yr, mn, dt);
connection.Execute("UPDATE MyTable SET exp_date=#exp where MyTable.id_no=#id",
new { exp = RegExp, id = AlmIDNo });
and done; fully safe from both injection and the (more likely in this case) issue of formatting data as strings.
This must be problem of the format you are specifying, like instead of month column you might be saving date value column.

In SQL I would like to subtract a date from a previous row date

The problem is that the dates are stored in the SQL database as nvarchar() and the times are stored in a separate column. I only have read access to this database, so I can't change the format. Besides, it would probably void our support if the manufacturer found out.
As I see I need to first combine the dates and times into one cell as a datetime and then subtract the previous row from the current.
ActualTime, ActualDate
5:30:26, 31-Dec-09
16:01:47, 31-Dec-09
17:35:50, 31-Dec-09
18:31:31, 31-Dec-09
18:51:03, 31-Dec-09
18:55:35, 31-Dec-09
19:26:53, 31-Dec-09
5:25:37, 1-Jan-10
5:38:36, 1-Jan-10
5:46:58, 1-Jan-10
6:27:00, 1-Jan-10
Several people have asked what language I was using. I was hoping to do all of this at the server. On the code side (C#) it's a trivial problem.
Like I said I am looking for an SQL Server server-side solution.
In Microsoft SQL Server, to convert your columns in a date you can
Select Cast( ActualDate + ' ' + ActualTime AS DateTime)
to compare between two dates
Select
Datediff(
second,
Cast('13-dec-2009 ' + '19:39:33' As DateTime),
Cast('13-dec-2009 ' + '19:26:33' As DateTime)
)
More on DATEDIFF (Transact-SQL) parameters.
And to get the difference from the current date/time use the GETDATE(),
Select
*,
oldness = DateDiff(
second,
GETDATE(),
Cast(ActualDate + ' ' + ActualTime AS DateTime)
)
From
your_table
Finally to do it between rows (for the whole table..),
Select *,
Cast(ActualDate + ' ' + ActualTime AS DateTime) as [fulldate],
DiffFromPrevious = Coalesce(
DateDiff(
second,
(
Select Top 1 Cast(ActualDate + ' ' + ActualTime AS DateTime) AS [fulldate]
From yourtable
Where Cast(ActualDate + ' ' + ActualTime AS DateTime) < Cast(t1.ActualDate + ' ' + t1.ActualTime AS DateTime)
Order By [fulldate] Desc
),
Cast(ActualDate + ' ' + ActualTime AS DateTime)
),
0)
From
yourtable t1
Order By
[fulldate] Asc
What language are you using, and what kind of Database is it? I'm not sure if the database has capabilities to do row manipulation within a query (subtracting one row from the other), so you would have to do this programmatically. I'm not sure what language you're using, but if it has a Date or Time API then you can use that to create a Date object. There should a function that returns the total number of seconds since a starting date (January 1, 1970 or something). You create your two Date objects, convert into number of seconds and then subtract them. You can then calculate the number of days between them.
If you're using PHP, I suggest you use the strtotime() function to convert it into a time object. Do this for both dates. The difference will give you the number of seconds between them.

How do I insert and query a DateTime object in SQLite DB from C#?

Consider this snippet of code:
string sDate = string.Format("{0:u}", this.Date);
Conn.Open();
Command.CommandText = "INSERT INTO TRADES VALUES(" + "\"" + this.Date + "\"" + "," +this.ATR + "," + "\"" + this.BIAS + "\"" + ")";
Command.ExecuteNonQuery();
Note the "this.Date" part of the command. Now Date is an abject of type DateTime of C# environment, the DB doesnt store it(somewhere in SQLite forum, it was written that ADO.NET wrapper automatically converts DateTime type to ISO1806 format)
But instead of this.Date when I use sDate (shown in the first line) then it stores properly.
My probem actually doesnt end here. Even if I use "sDate", I have to retrieve it through a query. And that is creating the problem
Any query of this format
SELECT * FROM <Table_Name> WHERE DATES = "YYYY-MM-DD"
returns nothing, whereas replacing '=' with '>' or '<' returns right results.
So my point is:
How do I query for Date variables from SQLite Database.
And if there is a problem with the way I stored it (i.e non 1806 compliant), then how do I make it compliant
The ADO.NET wrapper can't convert the DateTime values to ISO 8601 (not 1806) if you convert it to a string and put it in the query. You need to use parameters for that:
Command.CommandText = "INSERT INTO TRADES VALUES (#Date, #Atr, #Bias)";
Command.Parameters.Add("#Date", this.Date);
Command.Parameters.Add("#Atr", this.ATR);
Command.Parameters.Add("#Bias", this.BIAS);
Conn.Open();
Command.ExecuteNonQuery();
(Besides, you converted the DateTime value to a string and put in the sDate variable, but then you used the DateTime value to produce the SQL query anyway.)
The same applies when getting the data:
Command.CommandText = "SELECT * FROM <Table_Name> WHERE DATES = #Date";
Command.Parameters.Add("#Date", theDate);
About your second problem, if SQLite is anything close to SQL Server,
SELECT * From where Dates = "YYYY-MM-DD' will not return because it will probably implicitily convert YYYY-MM-DD to YYYY-MM-DD 00:00:00. You might need to add a range (e.g. greater or equal than today and smaller than tomrrow).
#Guffa, I am getting "Cannot Convert from System.DateTime to System.Data.DbType" on this line:
Command.Parameters.Add("#Date", this.Date);

Categories

Resources