combine date and time column problem - sql-server

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

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;

Datetime is NULL when time format differs

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 +' '......................

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

sql stored procedure execute command

I've created the following stored procedure on sql:
CREATE PROCEDURE Sp_generate_report (#YEAR INT,
#MONTH INT)
AS
DECLARE #CATEGORY VARCHAR(20)
DECLARE #BEGIN_DATE DATE
DECLARE #END_DATE DATE
BEGIN
SELECT #BEGIN_DATE = Cast(( Cast(#YEAR AS VARCHAR) + '-'
+ Cast(#MONTH AS VARCHAR) + '-' + '1' ) AS DATE)
SELECT #END_DATE = Cast(( Cast(#YEAR AS VARCHAR) + '-' +
Cast(#MONTH AS VARCHAR) + '-' + '32' ) AS DATE)
SELECT TOP 1 #CATEGORY = Name
FROM dbo.Profitible_categories(#BEGIN_DATE, #END_DATE)
INSERT INTO dbo.MONTHLY_SUMMARY_REPORTS
VALUES (#CATEGORY)
END
The procedure was created successfully, but when I try to execute it with the following command:
EXECUTE SP_GENERATE_REPORT 2012, 7
I get this error message:
Msg 241, Level 16, State 1, Procedure SP_GENERATE_REPORT, Line 8
Conversion failed when converting date and/or time from character
string.
thanks in advance for the help.
You can calculate the last day of the month without all that nasty string concatenation or trying to guess which month it is and pick the last day.
CREATE PROCEDURE dbo.Sp_generate_report
#YEAR INT,
#MONTH INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #BEGIN_DATE DATE = DATEADD(MONTH, #MONTH-1, CONVERT(DATE,
CONVERT(CHAR(4), YEAR) + '0101'));
DECLARE #END_DATE DATE = DATEADD(DAY, -1, DATEADD(MONTH, 1, #BEGIN_DATE));
INSERT INTO dbo.MONTHLY_SUMMARY_REPORTS
SELECT TOP (1) Name
FROM dbo.Profitible_categories(#BEGIN_DATE, #END_DATE);
END
GO

Resources