Unable know the exception in query - sql-server

I'm writing the below query in SQL Server
update time_tracker
set logout = GETDATE(),
totaltime = SUBSTRING(CONVERT(varchar(20), (LOGOUT - LOGIN),120),12,8) from Time_Tracker
where userid = 0138039
and CONVERT(Date, LOGIN) = CONVERT(Date, GETDATE());
Basically, when the user hits a logout button I'm trying to achieve the below.
Enter the logout datetime stamp in my logout column
Calculate the difference between the login and logout time and update the total time column, bu checking for today's date and the current user.
When I do this, I'm getting this exception:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.
Please let me know where I'm going wrong and how can I fix this.
Also when I run the below query
Select
SUBSTRING(CONVERT(varchar(20), (LOGOUT - LOGIN),120),12,8)
from
Time_Tracker;
It is working fine, I mean I'm getting the correct time output.
Thanks

You are trying to get hh:mm:ss from LOGOUT - LOGIN based on 12,8 in SUBSTRING function. And put them into float column.
I think it is better to store differences in integer datatype in milliseconds. Or use time datatype for that column.
Try to use DATEDIFF:
Select DATEDIFF(ms,LOGIN,LOGOUT) from Time_Tracker;
That will give you the time between two dates in milliseconds.
Or ALTER your column to time format.

Related

SQL DateTime Inserted Incorrectly From VB.NET

Have a table I'm logging information from a .NET program into.
The VB.NET app explicity dictates the format of the DATETIME string like below
responsedt = Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
I then pass this into an INSERT statement that updates my table, however even though the entire setup of the SQL Server is en-GB (British English) the DateTime has gone in the following format:
2019-09-05 19:09:34.823
This was done yesterday so actually should be
2019-05-09 19:09:34.823
The day and month should be switched around, I have tried performing an update on the table post process to get it to update using the following code
FORMAT (xa.daterequested, 'yyyy-dd-MM HH:MM:ss.fff', 'en-gb')
How while this works in a SELECT statement it doesn't seem to work when I do the UPDATE statement.
It is not ideal to have to update all the records dates after the initial INSERT so a solution to either the .NET side of the issue or the SQL would be appreciated as its pickling my head.
You have 2 options to prevent the error from happening again:
Keep dates as date/time data types instead of converting them to strings.
Use formats that are not language or settings dependent. In SQL Server these would be YYYYMMDD hh:mm:ss.msss OR YYYY-MM-DDThh:mm:ss.mss (notice the T between date and time)
To correct the dates already inserted you could use the format codes in the CONVERT function.
UPDATE t SET
daterequested = STUFF( STUFF( StringDate, 5, 0, SUBSTRING(StringDate,7,2)), 9, 2, '')
FROM YourTable t
CROSS APPLY( SELECT CONVERT( varchar(25), '20190905 19:09:34.823', 121) AS StringDate) AS x;

Snowsql two digit century start date cast issue

I want a result 2000-02-05 with below query in snowsql.
alter session set TWO_DIGIT_CENTURY_START=2000;
select cast ('05-FEB-00' as date) from dual;
But I am getting 0001-02-05.
I am using existing script to load date in snowflake which works for oracle. I know I can get expected result using to_date function but I don't want to do so. If I have to then I have change many place in script which is hectic.
I want solution using cast function. Do anyone know what is happening here?
You first need to specify the non-default date format for your input data. In the case of the example above:
alter session set date_input_format = 'DD-MON-YY';
Then
alter session set TWO_DIGIT_CENTURY_START=2000;
select cast ('05-FEB-00' as date) from dual;
yields:
2000-02-05

Uploading datetimeoffset column with only hour as timezone to SQL Server

I have a timestamp column having values like the following in my database:
2017-01-01 00:00:58.538-05
2017-01-01 00:16:58.54-05
The data type is varchar since datetime, datetime2 formats did not work. I need to convert this column to datetime format now. I just discovered about datetimeoffset. :(
However, the conversion still does not work as is, and I get an error. datetimeoffset wants to see at least -05:0 not only -05.
DECLARE #datevar datetimeoffset = '2017-01-01 00:00:58.538-05';
SELECT #datevar
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
What can be to solve this? Worst case scenario I tend use python to preprocess each file to add :0 at the end of each value, and then save the file, and then bulk upload every file in the folder at the end. However, each file has ~30 million rows, and there are 365 of them per year. So I really do not want to do that.
Again, the data is already uploaded, an easy and FAST way to do this would be appreciated. There are about 8 billion rows in the table now, so I do not know whether this can be done using SQL Server Management Studio.
You can do the :00 appending in sql itself
SELECT Cast(dates + ':00' AS DATETIMEOFFSET),
dates
FROM (VALUES ('2017-01-01 00:00:58.538-05'),
('2017-01-01 00:16:58.54-05')) tc (dates)
considering none of your dates has minutes part of timezone. If some dates has minutes part then it needs to be handled differently
In your table it should be something like
SELECT Cast(datecolumn + ':00' AS DATETIMEOFFSET),
datecolumn
FROM Yourtable
to update the table
update t set yourcol = Cast(yourcol + ':00' AS DATETIMEOFFSET)
FROM Yourtable
Then alter the table datatype to datetimeoffset and make sure you upload data with time part in offset

Compare dates in MS SQL using Convert

I want to do the correct way to get a date from a #parameter that contains the complete datetime, that user gets from a calendar from TFS File.
In the select I would want to use something like CONVERT(varchar(10), #FechaHasta.Value, 120) AS DATE01 and then get the only date, throwing out the time from the parameter.
For the next step, I would want to compare it with another date in WHERE clause, having this code :
Then, I would want to make this work on for looking for between two dates, and the last one, throwing out the time from the datetime.
Thanks.
I am assuming #FetchHasta is a datetime
CONVERT(VARCHAR(10), #FetchHasta, 101)
is what gets you just the date part. i.e. 10/28/2014 1:10 PM would simply become 10/28/2014.
Source
EDIT: Alternatively, How to return the date part only from a SQL Server datetime datatype

Problem in Getting the DateTime Variable from the Database

I used to get the Login Time of a user when he Logsin at the First Time to the Syatem, all the activities the user is doing will be stored under a seperate column called 'Activity'. My Problem is the User can LogOn to the System many times in a Particular Day, but i want to retrieve only the First Logon Time. The LogOn timings are appearing when i write a query for getting the Timings based on Activity are Like below.
Time User Activity
'3/23/2011 9:55:00AM' kk LogOn
'3/23/2011 5:30:00PM' kk LogOn
I write a Query to retrieve these values like this
Select StartDateTime,User,Activity from AgentLog where Activity='LogOn'. So, any one can give me Small help that how can i retrieve only the First LogOn time for the User given. I am Using Sql Server 2008, There will be Somany days, the User Logging On, so for every day i need to get the Logon Time
Get the earliest time for each day they logged in by using the following grouping:
Select min(StartDateTime)
from AgentLog
where Activity='LogOn' and
User = 'Username'
group by datepart(day, StartDateTime),
datepart(month, StartDateTime),
datepart(year, StartDateTime)
If you won't store times as a string but as a timestamp (in seconds) it would be easy to just select the data:
Select StartDateTime,Activity from AgentLog where Activity='LogOn' AND time>timeofday ORDER by time LIMIT 1
Where timeofday is the timestamp of the current day at midnight

Resources