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)
Related
The following code:
DECLARE #dateAsString AS nvarchar
SET #dateAsString = '2020-04-28T12:51:33.587Z'
DECLARE #dateObject as DATETIME
SET #dateObject = CAST(#dateAsString as DATETIME)
SELECT DATEDIFF(DAY, #dateObject, CURRENT_TIMESTAMP)
I get this error:
Msg 241, Level 16, State 1, Line 6
Conversion failed when converting date and/or time from character string
How can I ensure that the date stored in the database does not give me this error?
Convert and Cast didn't do the trick... please help!
The reason for the error is that you need to define the size of the #dateAsString nvarchar variable. When the size is not specified the default length is 1 and the actual value of the #dateAsString variable is 2.
Also, as an option, you may use CONVERT() with an appropriate date and time style:
DECLARE #dateAsString AS nvarchar(24)
SET #dateAsString = N'2020-04-28T12:51:33.587Z'
DECLARE #dateObject as DATETIME
--SET #dateObject = CAST(#dateAsString as DATETIME)
SET #dateObject = CONVERT(datetime, #dateAsString, 127)
SELECT DATEDIFF(DAY, #dateObject, CURRENT_TIMESTAMP)
Your code is ok, only your nvarchar was to small to hold you data
DECLARE #dateAsString AS nvarchar(28)
SET #dateAsString = '2020-04-28T12:51:33.587Z'
DECLARE #dateObject as DATETIME
SET #dateObject = CAST(#dateAsString as DATETIME )
SELECT DATEDIFF(DAY, #dateObject, CURRENT_TIMESTAMP)
GO
| (No column name) |
| ---------------: |
| 174 |
db<>fiddle here
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.
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
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
I Have a string like as given below
201004301342
Need to convert it into dd/mm/yy format
Can anyone help me please?
This will change the value to a datetime. A datetime has no format until you convert back to a string again.
You can use stuff to change the string value to 20100430 13:42 and then cast to datetime.
declare #Date varchar(12)
set #Date='201004301342'
select cast(stuff(stuff(#Date, 11, 0, ':'), 9, 0, ' ') as datetime)
if you want a string and start string is always with this format then
declare #date varchar(50)
set #date = '201004301342'
SELECT convert(varchar, cast(substring(#date, 1, 8) as datetime), 103)