Error converting nvarchar to float in SQL Server - sql-server

I want to view the session hours of previous 3 months in my SQL (hrs column is declared as nvarchar), I need to convert the data into float if I want to view the data of last 3 months but I am getting some errors
SELECT sum(convert(float, hrs))
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
SELECT sum(cast(hrs as float))
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
SELECT CAST(CAST (hrs AS NUMERIC(19,4)) AS INT)
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to numeric.
SELECT CAST(CAST (hrs AS int) AS INT)
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '02:00:00 ' to data type int.
I tried these four ways and failed in all of them, how I need to do this?

First, use date and time data types for datetime values. And you will avoid these and many other troubles and also save disk space, RAM, reduce number of reads and so on.
As for your problem. For Sql Server 2008+
DECLARE #companysonvinunitvenue TABLE (hrs NVARCHAR(10))
INSERT #companysonvinunitvenue VALUES ('02:00:00'),('21:31:03')
SELECT DATEPART(HOUR,CAST(hrs AS time))
FROM #companysonvinunitvenue
For other versions
DECLARE #companysonvinunitvenue TABLE (hrs NVARCHAR(10))
INSERT #companysonvinunitvenue VALUES ('02:00:00'),('21:31:03')
SELECT cast(LEFT(hrs,2) AS INT)
FROM #companysonvinunitvenue

Related

Converting date formats in sql

Recently I am facing a problem while working with date formats. In the table below I have following dates which is obtained while querying in microsoft SQL Server management studio 2014
select [Month Ending Date] from drug_practise
dates
12/1/2016
11/1/2016
10/1/2016
9/1/2016
8/1/2016
But I need to convert these dates into a proper format such as YYYY-mm-dd, so I used the following code:-
select convert(date,[Month Ending Date],103) from drug_practise
but it throws error as follows :-
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
Anyone can help me how to deal with the dates and avoid such errors ?
I guess you should try format 104 instead of 103 if the first 2 digits represent the day - at least this worked well with the examples provided:
DECLARE #t TABLE(myDateStr CHAR(10))
INSERT INTO #t VALUES
('12/1/2016')
,('11/1/2016')
,('10/1/2016')
,('9/1/2016')
,('8/1/2016')
SELECT myDateStr, TRY_CONVERT(DATE, myDateStr, 104) AS myDate, TRY_CONVERT(VARCHAR(10), TRY_CONVERT(DATE, myDateStr, 104), 23) AS myDateStrNew
FROM #t
If the first two digits represent the month, you can try using format 0 instead:
DECLARE #t TABLE(myDateStr CHAR(10))
INSERT INTO #t VALUES
('12/1/2016')
,('11/1/2016')
,('10/1/2016')
,('9/1/2016')
,('8/1/2016')
SELECT myDateStr, TRY_CONVERT(DATE, myDateStr, 0) AS myDate, TRY_CONVERT(VARCHAR(10), TRY_CONVERT(DATE, myDateStr, 0), 23) AS myDateStrNew
FROM #t

How to solved datetime conversion error in SQL Server

Here is my code:
DECLARE #dayscount int
SET #dayscount = CAST(DATEDIFF(day, CONVERT(VARCHAR(20), '21/02/2021', 103), CONVERT(VARCHAR(20), '22/02/2021',103)) AS int)
SELECT #dayscount
I get this error:
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string
If you use the CONVERT function, the data type should be date type instead of varchar type.
select CAST(DATEDIFF(day, CONVERT(date, '21/02/2021', 103), CONVERT(date, '22/02/2021',103)) AS int)

How to fix (Arithmetic overflow error converting expression to data type datetime) error in SQL Server

I have created a procedure for the purpose of fetching the yesterday data from an Oracle database table and insert it into a SQL Server 2012 table.
Using the following
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT
LEAD(CONVERT(VARCHAR, CONVERT(DATETIME, '01-JAN-1970 03:00:00', 120) + [DAT_CLOSEDATE] / (24 * 60 * 60), 120), 1, CONVERT(VARCHAR, CONVERT(DATETIME, '01-JAN-1970 03:00:00', 120) + [DAT_CLOSEDATE] / (24 * 60 * 60), 120)) OVER (PARTITION BY [TXT_TICKETNUMBER] ORDER BY [DAT_CLOSEDATE]) AS [CLOSE_DATE]
INTO #Temp
FROM OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE ,TXT_TICKETNUMBER
FROM SCHEME.TABLE')
WHERE
[DAT_CLOSEDATE] = DATEADD(d, -1, GETDATE())
SELECT * FROM #Temp
Everything is working as expected when I don't use the WHERE condition.
But once I use the WHERE condition, the following error appears
Msg 8115, Level 16, State 2, Line 4
Arithmetic overflow error converting expression to data type datetime.
NOTE:
The DAT_CLOSEDATE column datatype in the Oracle table is float and its datetime in sql server .
I used the LEAD and CONVERT functions in order to convert its values to be a datetime datatype
I have tried to convert it to date datatype as following.
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT
lead(convert(varchar,convert(date,'01-JAN-1970 03:00:00',120) +
[DAT_CLOSEDATE]/(24*60*60), 120),1,convert(varchar,convert(date,'01-JAN-
1970 03:00:00',120) + [DAT_CLOSEDATE]/(24*60*60), 120)) over(partition by
[TXT_TICKETNUMBER] order by [DAT_CLOSEDATE])AS [CLOSE_DATE]
INTO #Temp
FROM OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE ,TXT_TICKETNUMBER
FROM SCHEME.TABLE')
WHERE [DAT_CLOSEDATE] = DATEADD(d,-1,GETDATE())
SELECT * FROM #Temp
But I got this error
Msg 206, Level 16, State 2, Line 4
Operand type clash: date is incompatible with float
sample data for DAT_CLOSEDTE column in the oracle table which is FLOAT
DAT_CLOSEDATE
1531038410
1531038433
1531038438
1531038447
1531038449
1531038450
1531038506
1531038506
One of the resolution am looking for is I expect OPENQUERY syntax to be something like the following:
OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE, TXT_TICKETNUMBER
FROM SCHEME.TABLE
WHERE [DAT_CLOSEDATE] = trunc(sysdate)-1')
but it needs to be converted from FLOAT to DATE data type first.
Here's an example snippet that uses an extra sub-query to transform the FLOAT to a DATETIME.
Which makes further calculations easier.
Since it's an example, the insert into a temp table isn't used.
declare #Table table (TXT_TICKETNUMBER VARCHAR(30), DAT_CLOSEDATE FLOAT);
insert into #Table (TXT_TICKETNUMBER, DAT_CLOSEDATE) values
('foo000042', ((CONVERT(float, DATEADD(hour,-24,GETDATE()))*86400.0)-(25567.0*86400))),
('foo000042', ((CONVERT(float, DATEADD(hour,-23,GETDATE()))*86400.0)-(25567.0*86400))),
('bar000042', ((CONVERT(float, DATEADD(hour,-22,GETDATE()))*86400.0)-(25567.0*86400))),
('bar000042', ((CONVERT(float, DATEADD(hour,-21,GETDATE()))*86400.0)-(25567.0*86400)));
SELECT
TICKETNUMBER,
CLOSEDATETIME,
DAT_CLOSEDATE,
LEAD(CloseDatetime) OVER (PARTITION BY TICKETNUMBER ORDER BY CLOSEDATETIME) AS NextCLOSEDATETIME
FROM
(
select
TXT_TICKETNUMBER AS TICKETNUMBER,
DATEADD(hour,3,CONVERT(datetime,25567.0+(DAT_CLOSEDATE/86400.0))) AS CLOSEDATETIME,
DAT_CLOSEDATE
from
(
-- put the openquery here instead
select TXT_TICKETNUMBER, DAT_CLOSEDATE
from #Table
) q1
) q2
WHERE CAST(CLOSEDATETIME AS DATE) = CAST(DATEADD(day,-1,GETDATE()) AS DATE)
But if you would change that Oracle query to transform that "DAT_CLOSEDATE" to a string.
For example in the YYYY-MM-DD HH24:MI:SS format.
Then that would probably makes the conversion to a T-SQL DATETIME a tad easier.

SQL Server 2008: Convert truncated string to DATETIME and return those within 24 hours of CURRENT_TIMESTAMP

SO! I've a tricky set of data I'm working with and I've got it down to what I hope is the last part.
The goal is to return records from a 24 hour period. Column notes is varchar and contains the date I need to check against. I've truncated the datetime portion Notes and converted it to ISO8601 but I cannot seem to get it to check against >= DATEADD(day, -1, GETDATE())
Column data sample: Record updated: 04/06/2009 12:00:00 AM
My initial query attempt:
SELECT OrderNumber,
SUBSTRING(notes, 15, 35) as notes_truncated, //verify we got the complete date/time for conversion
CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126) AS convertTo_ISO8601 // convert it to recognizable datetime
FROM table
WHERE CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126) >= DATEADD(day, -1, GETDATE()) // substring -> convert -> compare against today's date and return those from within 24 hours
AND notes IS NOT NULL // necessary parameter
AND notes LIKE '%returnMe%'; // necessary parameter
errors: Conversion failed when converting date and/or time from character string
DECLARE #sillyString datetime;
SET #sillyString = CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126);
SELECT SUBSTRING(notes, 15, 35) as notes_truncated,
CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126) AS UsingConvertTo_ISO8601
FROM table
WHERE #sillyString >= DATEADD(day, -1, GETDATE())
AND notes IS NOT NULL
AND notes LIKE '%returnMe%';
error: Invalid column name 'notes'
DECLARE #value varchar(20);
DECLARE #sqlText nvarchar(1000);
DECLARE #sillyString datetime;
SET #value = 'notes'
SET #sillyString = CONVERT(nvarchar(30), SUBSTRING(#value, 15, 35), 126);
SELECT SUBSTRING(notes, 15, 35) as notes_truncated,
#sillyString AS UsingConvertTo_ISO8601
FROM table
WHERE notes IS NOT NULL
AND notes LIKE '%returnMe%';
errors: UsingConvertTo_ISO8601 returns with a value of 1900-01-01 00:00:00.000 so then doing modifying the WHERE to WHERE #sillyString >= DATEADD(day, -1, GETDATE()) AND notes IS NOT NULL AND notes LIKE '%returnMe%' returns 0 records.
Your assistance is much appreciated!
Try a quick check to see if the string is not a date for any records you will be returning:
SET DATEFORMAT ymd -- make sure the date part is in the same order as 126 (4) ISO8601
SELECT OrderNumber,
SUBSTRING(notes, 15, 35) as notes_truncated
FROM table
WHERE ISDATE(SUBSTRING(notes, 15, 35)) = 0
AND notes IS NOT NULL // necessary parameter
AND notes LIKE '%returnMe%'; // necessary parameter

Conversion failed when converting date and/or time from character string - Msg 241, Level 16, State 1,

I keep getting the following error to my code when I either try to set it as cast() or convert(). Nothing seems to work.
Query:
SELECT TOP 100
*
FROM [OptionsDW].[dbo].[Octagon5]
WHERE CONVERT(datetime2, CurrDate, 121)
BETWEEN CAST('2010-01-01' AS date) AND CAST('2010-06-31' AS date)
Result:
Msg 241, Level 16, State 1, Line 2 Conversion failed when converting
date and/or time from character string.
I know there are many similar queries but none of them helped with my problem.
There are only 30 days in June so CAST('2010-06-31' AS date) in your where statement will fail

Resources