DateTime Conversions Issue - sql

My table in the DB has the following format yyyy-mm-dd HH:MM:SS. but the required format for a varchar data type is dd-mm-yyyy HH:MM:SS. when I change this in the query below the code runs but it returns nothing as the table date format doesn't match the varchar data type.
I assume it's a simple data conversion but I'm quite new to this and not sure on how to get around it.
DECLARE #LastxDays TABLE (DateForReport datetime)
DECLARE #DateForReport datetime
DECLARE #Results TABLE (DateForReport DateTime,
Currency VARCHAR(20),
TotalTransactionsIn Decimal(10,2),
TotalTransactionsOut Decimal(10,2),
TotalBalances Decimal(10,2))
-- SET initial date
SET #DateForReport = CAST('26-05-2022 17:00:00' as DATETIME)
PRINT #DateForReport
-- Add a row for each day of the year up to yesterday
WHILE(#DateForReport < dateadd(dd,-1, getdate()))
BEGIN
INSERT INTO #LastxDays VALUES (#DateForReport)
SET #DateForReport = DATEADD(day, 1, #DateForReport)
END
my table result is the following:
|Date | Name |Transaction in |Transaction out|
|2022/26/05|***** |***** |***** |

Related

Convert Varchar field to datetime in SQL Server

I am trying to convert varchar date to date time field and having a really hard time. It is giving me:
Conversion failed when converting date and/or time from character string.
or
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I have 2 datetime formats below :
Date field looks like 21-12-2009, 05-10-2005 etc
Date field looks like 19-03-2018 14:59
select cast(convert(varchar,Stg_hw.date_of_birth,110)as date)
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
select CONVERT(datetime,LEFT(date_of_birth,2)+SUBSTRING(Stg_hw.date_of_birth,4,2)+SUBSTRING(Stg_hw.date_of_birth,7,4))
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
select cast(Stg_hw.date_of_birth as date)
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
CONVERT(DATETIME, DateFieldColumnName, 103) can help to convert those 2 format to datetime.
Sample exection:
CREATE TABLE TestTable (DateVal VARCHAR (20));
INSERT INTO TestTable (DateVal) VALUES
('21-12-2009'), ('05-10-2005'), ('19-03-2018 14:59');
SELECT CONVERT(DATETIME, DateVal, 103) AS Result
FROM TestTable
Please find the working demo on db<>fiddle

Conversion failed date and/or time from character string

the output is a combination from two column and need to convert into date. Data source is numeric. The code works well for the first 100,000 and and error occur after 409,560. Error as "Conversion failed when converting date and/or time from character string."
SELECT
CASE WHEN LEN(OR6) = 6 THEN
CAST(CONCAT(SUBSTRING(CONVERT(VARCHAR(10),ORT),1,4),SUBSTRING(CONVERT(varchar(10),OR6),3,2),SUBSTRING(CONVERT(varchar(10),OR6),1,2))AS DATE)
WHEN LEN(OR6) = 5 THEN
CAST(CONCAT(SUBSTRING(CONVERT(VARCHAR(10),ORT),1,4),SUBSTRING(CONVERT(varchar(10),OR6),2,2),'0',SUBSTRING(CONVERT(varchar(10),OR6),1,1))AS DATE)
ELSE NULL
END AS ORI_MAT_DT ,DATE1 = OR6 ,DATE2 = ORT
FROM DATETABLE
This is the original source database:
ROW OR6 ORT
409,559 10611 2011152
409,560 50618 2018156
409,561 10615 2015152
409,562 50618 2018156
EXPECTED RESULT:
ORI_MAT_DT DATE1 DATE2
2001-08-15 150801 2001227
You can use a little math to get the values you want from the numeric values in OR6 and ORT, and then use DateFromParts to construct the date:
Source data:
DECLARE #Date1 numeric(10,2) = 150801,
#Date2 numeric(10,2) = 2001227
Query:
SELECT DATEFROMPARTS(
#Date2 / 1000, -- Get the year
(#Date1 % 10000 - #Date1 % 100) / 100, -- Get the month
#Date1 / 10000 -- Get the day
) As Date
Result:
Date
2001-08-15
The DateFromParts functions takes int values representing the year, month, and day and construct a Date object. Since it takes int, SQL Server will implicitly convert the numeric values you get from the calculations to int by truncating the decimal part.

Converting a varchar column to datetime

I have a table that has a column for dateofbirth varchar(10). All the data inside is stored like this '02/01/1990'.
I need to convert it to datetime. I've tried
CAST(DateofBirth AS DATEITME) AS BirthDate
But I keep getting this error when I try importing:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value"
I need it like this:
1990-02-01 00:00:00:000
SELECT CONVERT(Datetime, '2011-09-28 18:01:00', 120) -- to convert it to Datetime SELECT CONVERT( VARCHAR(30), #date ,105) -- italian format [28-09-2011 18:01:00] + ' ' + SELECT CONVERT( VARCHAR(30), #date ,108 ) -- full date [with time/minutes/sec]
You need to convert a Varchar in format MM/DD/YYYY to a Datetime.
Sql server recognizes a set of predefined date formats that it is able to automatically parse. See this cheat list.
Your input format corresponds to sql server date format 101, hence you can do :
SELECT CONVERT(Datetime, '02/01/1990', 101)
If you try to do it in sql query there is syntax to do it .
Here a link ..
SQL Server Convert Varchar to Datetime
Your cast statement works for me:
Declare #dateofbirth varchar(10) = '02/01/1990'
select cast(#dateofbirth as datetime)AS BirthDate
Result:
BirthDate
1990-02-01 00:00:00.000

BigInt won't convert to proper date format

So I have a query I'm trying to write where there are two columns that will have variable results. One is date and one is time. My query will look like
Select Schedule ID , Job_Name , next_run_date , next_run_time
The values will vary depending on what database I'm running against. For example, [next_run_date] might = 20181014 and [next_run_time] might read 1000 which would be 1am. But if I run it on a different server, it could have a completely different set of values, but just the same format.
I've unsuccessfully tried to convert the columns to date/time format by using
CONVERT(varchar(10),CONVERT(date,[next_run_date],110),110) AS 'Next Run'
And just get 'Explicit conversion from data type int to date is not allowed'
What I'd like it to display is [next_run_date] might = 10-14-2018 and [next_run_time] = 01:00. Just unsure how to convert this correctly. I do not have to write privs to the database. If I read correctly, at least for the date column, I would have to convert from Bigin to Varchar to ToDate, but unclear how to fully write that.
For the time field you can stuff a : in it.
And a FORMAT for the times below 10 AM.
And the date part can be done with 2 casts and a CONVERT or a FORMAT.
The date from an INT to a VARCHAR in the 'mm-dd-yyyy' format:
CONVERT(VARCHAR(10), CAST(CAST([next_run_date] AS VARCHAR(8)) AS DATE), 110)
The time from an INT to a VARCHAR in the 'hh:mi' format:
STUFF(CAST(FORMAT([next_run_time],'000000') AS VARCHAR(4)),3,0,':')
Example snippet:
DECLARE #Table TABLE (next_run_date INT, next_run_time INT);
INSERT INTO #Table (next_run_date, next_run_time) VALUES
(20180901, 13500)
,(20181015, 134200)
;
SELECT
CONVERT(VARCHAR(10), CAST(CAST([next_run_date] AS VARCHAR(8)) AS DATE), 110) AS [Next Run Date],
STUFF(CAST(FORMAT([next_run_time],'000000') AS VARCHAR(4)),3,0,':') AS [Next Run Time]
FROM #Table
Returns:
Next Run Date Next Run Time
------------- -------------
09-01-2018 01:35
10-15-2018 13:42
You need to convert the bigint to a varchar first, then to a date:
CONVERT(date,CONVERT(varchar(10),[next_run_date]),110) AS 'Next Run'
You could also break up the number into parts and craft a date and time.
DECLARE #Date INT=20181014
DECLARE #Time INT=123456
SELECT CONVERT(DATE,
SUBSTRING(CONVERT(VARCHAR(20),#Date),1,4)+'/'+
SUBSTRING(CONVERT(VARCHAR(20),#Date),5,2)+'/'+
SUBSTRING(CONVERT(VARCHAR(20),#Date),7,2)
) AS [Date]
SELECT CONVERT(TIME,
SUBSTRING(CONVERT(VARCHAR(20),#Time),1,LEN(CONVERT(VARCHAR(20),#Time))-4)+':'+
SUBSTRING(CONVERT(VARCHAR(20),#Time),LEN(CONVERT(VARCHAR(20),#Time))-3,2)+':'+
SUBSTRING(CONVERT(VARCHAR(20),#Time),LEN(CONVERT(VARCHAR(20),#Time))-1,2)
) AS [Time]
select convert(datetime, cast(20181014 as varchar), 102)
Note :
CAST is part of the ANSI-SQL specification; whereas, CONVERT is not.
In fact, CONVERT is SQL implementation specific. CONVERT differences
lie in that it accepts an optional style parameter which is used for
formatting.

SELECT a datetimeoffset field by datetime

I have a table with a datetimeoffset field which is primary key. I want to filter my table with a datetime.
For example my table has:
2016-04-27 23:30:00.7684500 +03:00
2016-04-28 00:30:00.7684500 +03:00
In local time format, first row mean 2016-04-28 02:30:00 and second row means 2016-04-28 03:30:00. I mean two of them in date: 2016-04-28.
When I wanted to report transactions in date 2016-04-28, I get only second row.
declare #fromDate datetime
select #fromDate = '2016-04-28 00:00:00'
select * from MYTABLE where dto > #fromDate
Because, sql look at UTC time in datetimeoffset field.
I can get what I really want like this:
declare #fromDate datetime
select #fromDate = '2016-04-28 00:00:00'
select * from MYTABLE where CAST(dto as datetime) > #fromDate
First and second row are coming.
The question is: does performance suffer due to casting? System looking and casting every row (sequential read), even if dto is the primary key?
Is there any better way?
Many thanks...
If your offset (+3) is a constant, you can try this:
declare #fromDate datetime
select #fromDate = '2016-04-28 00:00:00'
select * from MYTABLE where dateadd(hour, 3, dto) > #fromDate
Or you can use TODATETIMEOFFSET
as follow:
select * from MYTABLE where TODATETIMEOFFSET(dto, '03:00') > #fromDate
Absolutely ... I would recommend adding a Calculated Field to the table. This way, the conversion takes place automatically in SQL and there is not CAST or CONVERT needed in the query. Do a search on Calculated Field and insert your code
CONVERT(DATETIME, dto, 109)
or
TRY_CONVERT(DATETIME, dto, 109)
I would use TRY_CONVERT as you can specifically set the format of the DateTime for your new calculated field and if for some reason, dto is not a valid date, it will insert NULL as opposed to failing.