Datetime is NULL when time format differs - sql-server

I have specific time scenario which can be 4 digit, 6 digit or can be NULL or string as mentioned below. Here in scenario 3 & 4 my method of calculating datetime is not working and coming as NULL
Is there any way to get date with 00:00:00:000 as time for case 3 & 4?
& for 1 it should be 10:02:00:000
DECLARE #DATE VARCHAR(10) =CAST(GETDATE() AS DATE)
DECLARE #Time1 VARCHAR(10) = '1002'
DECLARE #Time2 VARCHAR(10) = '160634'
DECLARE #Time3 VARCHAR(10) = '0900XX'
DECLARE #Time4 VARCHAR(10) = ''
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time1), 2)
+ ':' + SUBSTRING(#Time1, 3, 2)
+ ':' + RIGHT(rtrim(#Time1), 2)) , TRY_CONVERT(TIME, #Time1), #Time1 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time2), 2)
+ ':' + SUBSTRING(#Time2, 3, 2)
+ ':' + RIGHT(rtrim(#Time2), 2)) , TRY_CONVERT(TIME, #Time2), #Time2 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time3), 2)
+ ':' + SUBSTRING(#Time3, 3, 2)
+ ':' + RIGHT(rtrim(#Time3), 2)) , TRY_CONVERT(TIME, #Time3), #Time3 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time4), 2)
+ ':' + SUBSTRING(#Time4, 3, 2)
+ ':' + RIGHT(rtrim(#Time4), 2)) , TRY_CONVERT(TIME, #Time4), #Time4 AS Time

I would, personally, "pad out" the values to be 6 digits, inject the : characters, and then use TRY_CONVERT. Then you use ISNULL to return midmight for failed converions:
SELECT ISNULL(TRY_CONVERT(time(0),STUFF(STUFF(RIGHT('000000' + V.VarcharTime,6),5,0,':'),3,0,':')),'00:00:00')
FROM (VALUES(#Time1),
(#Time2),
(#Time3),
(#Time4))V(VarcharTime);
If 1002 is meant to be 10:02:00 rather than 00:10:02 then pad on the right, rather than the left:
SELECT ISNULL(TRY_CONVERT(time(0),STUFF(STUFF(LEFT(V.VarcharTime+'000000',6),5,0,':'),3,0,':')),'00:00:00')
FROM (VALUES(#Time1),
(#Time2),
(#Time3),
(#Time4))V(VarcharTime);

..................
DECLARE #Time4 VARCHAR(10) = ''
select #Time1 = concat(cast(#Time1 as varchar(8)), replicate('0', 8));
select #Time2 = concat(cast(#Time2 as varchar(8)), replicate('0', 8));
select #Time3 = concat(cast(#Time3 as varchar(8)), replicate('0', 8));
select #Time4 = concat(cast(#Time4 as varchar(8)), replicate('0', 8));
SELECT TRY_CONVERT(DATETIME, #DATE +' '......................

Related

Convert varchar string to datetime

I am having an issue converting below to a DateTime, I am only able to get the date portion of the string. My goal is to get both the date & time.
declare #col varchar(14) = '20220602235900';
select CONVERT(datetime, CAST(#col AS varchar(8)), 121) dtimecre
Steps:
Read the documentation for CONVERT and pick the closest format to use
Do some string manipulation to get the desired format
Convert.
DECLARE #col varchar(14) = '20220602235900';
SELECT
CONVERT(date, SUBSTRING(#col,1,8), 121) [Date Component]
, CONVERT(time, SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 8) [Time Component]
, CONVERT(datetime, SUBSTRING(#col,1,4) + '-' + SUBSTRING(#col,5,2) + '-' + SUBSTRING(#col,7,2) + ' ' + SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 120) [DateTime Representation];
Returns:
Date Component
Time Component
DateTime Representation
2022-06-02
23:59:00.0000000
2022-06-02 23:59:00.000
And another variant with a smaller amount of SUBSTRING:
DECLARE #col varchar(14) = '20220602235900';
SELECT DateComponent = CAST(DatePartString AS DATE),
TimeComponent = CAST(TimePartString AS TIME),
DateAndTime = CAST(DatePartString + ' ' + TimePartString AS DATETIME)
FROM (VALUES(#col)) AS O (DateColumn)
CROSS APPLY (
SELECT DatePartString = LEFT(DateColumn, 8),
TimePartString = FORMAT(CAST(SUBSTRING(DateColumn, 9, 6) AS INT), '##:##:##')
) AS String;

while passing bigger date differnce getting erro in sql

I have stored procedure like this on my DB:
ALTER procedure [dbo].[performance]
(#startdate nvarchar(100), #enddate nvarchar(100)
as begin
declare #date1 nvarchar(100) = convert(varchar, #startdate+' 00:00:00.000', 120)
declare #date2 nvarchar(100) = convert(varchar, #enddate+' 23:59:59.000', 120)
set NOCOUNT on;
select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as TotalDiff,
[dbo].[testfunction](
CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as Average
from Transaction_tbl t
left join VType_tbl v
on t.vtid=v.vtid
left join Location_tbl l
on t.Locid=l.Locid
where t.Locid in
(select t1.Locid from Transaction_tbl t1)
and dtime between '' + #date1 +'' and ''+ #date2 +''
and Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
my testfunction ike this:
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour integer,
#Mns integer,
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(2), convert(int, #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(6), #second)), 6)
RETURN #Average
END
if i pass start date:2013-06-01 and end date:2013-08-01 then getting proper out put
if i pass start date:2010-06-01 and end date:2013-08-01 (bigger date difference) then getting error:
Arithmetic overflow error converting numeric to data type varchar.
i know having some problem with my function.but i am not able find out what is the issue with my function.if any one please help me to find out
try this .. i think your #Mns should be the problem
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour decimal(18,2),
#Mns decimal(18,2),
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(8), convert(decimal(18,2), #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(10), #second)), 6)
RETURN #Average
END

storing current date time with milisec in varchar column - mssql

storing current date time with milisec in varchar column - mssql
i do have a varchar max column
i want to store current date with mili seconds in a column
with Concatenating the day-month-year-h-m-s-ms
Like
2304201310151515
Try this :-
SELECT REPLACE(CONVERT(varchar(max), getdate(), 103), '/', '')+
REPLACE(CONVERT(varchar(max), getdate(), 114), ':', '')
Try this one -
DECLARE #date DATETIME
SELECT #date = GETDATE()
SELECT
REPLACE(CONVERT(VARCHAR(20), #date, 104), '.', '') +
LEFT(REPLACE(CONVERT(VARCHAR(20), #date, 114), ':', ''), 8)
DECLARE #text VARCHAR(20)
SELECT #text = '2304201310151515'
SELECT
CAST(
SUBSTRING(#text, 5, 4) +
SUBSTRING(#text, 3, 2) +
SUBSTRING(#text, 1, 2) AS DATETIME)
+
CAST(
SUBSTRING(#text, 9, 2) + ':' +
SUBSTRING(#text, 11, 2) + ':' +
SUBSTRING(#text, 13, 2) + '.' +
SUBSTRING(#text, 15, 2) AS TIME)
I don't know what you use the varchar column for, but I highly recommend you use the yyyymmddhhmmssmmm format as it is sortable.
declare #date datetime = '20130423 10:15:15.15' -- Works in SQL 2008
select replace(replace(replace(replace(convert(varchar /* defaults to 30 char*/, #date, 121)
, '-', '')
, ':', '')
, '.', '')
, ' ', '')
Also, if you really want 2 digit milliseconds, then limit the characters returned from the convert function to varchar(22).
declare #date datetime = '20130423 10:15:15.15' -- Works in SQL 2008
select replace(replace(replace(replace(convert(varchar(22), #date, 121)
, '-', '')
, ':', '')
, '.', '')
, ' ', '')

Formatting date and time when they are not received as datetime

I am receiving a date and a time field from an access database and they are separate varchar fields. I am importing the data into an sql database. I want to display the data as a date time field but I can't get the data to format in the normal manner. I have come up with a substring to format the data but I am having problems getting it either into a cursor or a loop to get all of the data to update. I want to format my import table first before I move it to another table in sql. Here is code that I have for the date and time to format it. Any help would be appreciated.
Time
declare #result varchar(10), #time varchar(6), #hour varchar(2), #min varchar(2), #sec varchar (2);
Select #time = time_of_call from import
Set #hour = substring(#time, 1, 2);
Set #min = substring(#time, 3, 2);
Set #sec = substring(#time, 5, 2);
If #hour < '12'
Set #result = #hour + ':' + #min + ' AM';
else if #hour >= '12'
Set #result = #hour + ':' + #min + ' PM';
Select #result;
Date
declare #result varchar(12), #date varchar(8), #year varchar(4), #month varchar(2), #day varchar(2);
Select #date = date_of_call from import
Set #year = substring(#date, 1, 4);
Set #month = substring(#date, 5, 2);
Set #day = substring(#date, 7, 2);
Set #result = #month + '/' + #day + '/' + #year;
Select #result
--- some sample data
create table import (time_of_call varchar(6), date_of_call varchar(8));
insert into import values ('101112', '20121110');
insert into import values ('134526', '20130201');
--- the query
select cast(date_of_call + ' ' +
substring(time_of_call, 1, 2) + ':' +
substring(time_of_call, 3, 2) + ':' +
substring(time_of_call, 5, 2) as datetime) AsDateTime,
cast(date_of_call + ' ' +
substring(time_of_call, 1, 2) + ':' +
substring(time_of_call, 3, 2) + ':' +
substring(time_of_call, 5, 2) as datetime) AsString
from import;
----------------------- -----------------------
AsDateTime AsString
----------------------- -----------------------
2012-11-10 10:11:12.000 2012-11-10 10:11:12.000
2013-02-01 13:45:26.000 2013-02-01 13:45:26.000

combine date and time column problem

Using SQL Server 2005
Date Time
20060701 090000
20060702 020000
20060703 180000
...
Date and Time datatype is varchar
Tried Query
select Convert(datetime, Convert(char(10), date, 103) + ' ' + Convert(char(8), time, 108), 103) from table
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, date)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, time), time)
as datetime) from table
It showing error as out of range value.
How to solve this issue.
Need Sql Query Help
First off, why are you storing a DATETIME in a VARCHAR?
This should be able to help
DECLARE #Table TABLE(
Val VARCHAR(20)
)
INSERT INTO #Table (Val) SELECT '20060701 090102'
INSERT INTO #Table (Val) SELECT '20060702 020000'
INSERT INTO #Table (Val) SELECT '20060703 180000'
SELECT *,
CAST(SUBSTRING(Val,1,8) + ' ' + SUBSTRING(Val,10,2) + ':' + SUBSTRING(Val,12,2) + ':' + SUBSTRING(Val,14,2) AS DATETIME)
FROM #Table
I came across a similar issue a few years ago, when importing HL7 messages. Here is a copy of the function I used. It creates a DateTime string with the time component correctly separated into hh:mm:ss, which is needed for the cast to DateTime.
CREATE FUNCTION fn_StringDateTietoDateTime
(
#Date varchar(15)
)
RETURNS datetime
AS
BEGIN
DECLARE #Result DATETIME
SET #Result = NULL
If len(#Date) > 0
BEGIN
SELECT #Result = CAST(SUBSTRING(#hl7date, 1, 8) + ' ' + SUBSTRING(#hl7date, 10, 2) + ':' +
SUBSTRING(#date, 12, 2) + ':' + SUBSTRING(#date,14, 2) AS DATETIME)
END
RETURN #RESULT
END

Resources