I'm trying to concatenate a column's date to a fixed time of the day and then CAST the whole thing as DATETIME.
The fixed time is 5:30am.
The date column I'm using needs to be adjusted as it shows the end date/time of when something ran; I want to use the start date/time.
The start date/time time is not available as its own column, but I have another column that has the duration the process took in seconds, so I can use DATEADD to roll the end date/time back to the start date/time.
Here's the full statement:
CAST(CONVERT(VARCHAR(10), DATEADD(ss,-ConfTask.[LastExecutedDuration], ConfTask.[LastExecutedDate]), 103) + ' ' + '05:30' as DATETIME)
Here's the error message I'm receiving:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
I've tried testing these statements to investigate the issue, but they all run OK on their own:
CAST(CONVERT(VARCHAR(10), GETDATE(), 103) + ' ' + '05:30' as DATETIME)
CAST('2017-03-02' + ' ' + '05:30' as DATETIME)
DATEADD(ss,-ConfTask.[LastExecutedDuration], ConfTask.[LastExecutedDate])
I'm a bit stuck on how to get round this issue. Any help would be much appreciated.
Clearly, you must have some unexpected values in the column.
I would suggest finding them using a query such as this:
SELECT LastExecutedDuration, LastExecutedDate
FROM ConfTask
WHERE TRY_CONVERT(datetime,
CONVERT(VARCHAR(10),
DATEADD(second,
-ConfTask.[LastExecutedDuration],
ConfTask.[LastExecutedDate]
)
103
) + ' ' + '05:30')
)
You can also simplify the logic, by just using date functions:
select dateadd(minute,
5 * 60 + 30,
convert(datetime,
convert(date,
dateadd(second,
- ConfTask.LastExecutedDuration
ConfTask.LastExecutedDate
)
)
)
)
This worked:
CONVERT(DATETIME, CONVERT(CHAR(8), DATEADD(ss,-ConfTask.[LastExecutedDuration], ConfTask.[LastExecutedDate]), 112)) + ' ' + CONVERT(CHAR(8), '05:30:00', 108)
Related
I have a column type time(7).
What i want is to add in time column to date.
i manage to get the only date using GETDATE() function but i fail to add the time part next to date.
Query:
SELECT [Compay]
,[Time]
,CAST(GETDATE() AS DATE) AS Today
,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) AS Today_AS_Nvarchar
,CAST([Time] AS NVARCHAR) AS Time_AS_Nvarchar
,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) + ' ' + CAST([Time] AS NVARCHAR) AS Today_Time_AS_Nvarchar
,CONVERT(datetime,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) + ' ' + CAST([Time] AS NVARCHAR),103)
FROM [Testing_Env].[dbo].[Com_CD_Test]
Error:
Conversion failed when converting date and/or time from character string.
The error arise on CONVERT(datetime,CAST(CAST(GETDATE() AS DATE) AS NVARCHAR) + ' ' + CAST([Time] AS NVARCHAR),103)
is there any easier/orthodox way to achieve it?
You can't add the new date and time data types together like you can the old data types; personally I think this is also better as it stop people treating dates and times like a numerical value.
Assuming you have a date column and a time column you have a few of options. The first is to CAST/CONVERT both to a datetime and then "add" them together. Because the "old" data types work more like numerical values this works, however, you will lose accuracy of your time value if it has a precision of 3 or higher (as datetime is only accurate to 1/300 seconds):
DECLARE #TimeValue time(7) = '17:52:12.1234567',
#DateValue date = '20211016';
SELECT CONVERT(datetime, #DateValue) + CONVERT(datetime, #TimeValue);
If loosing accuracy isn't an option, then you could to use conversion on the date value and use DATEDIFF and DATEADD. For a time(7) you'll want to be using nanoseconds (as microseconds isn't accurate enough). Unfortunately this poses another problem; DATEADD can't handle bigint values (still) and there is no DATEADD_BIG (like there is DATEDIFF_BIG), so this becomes overly complex. You need to first get the difference in milliseconds, and then add the remainder in nanoseconds to still be accurate to 1/1000000 of a second:
DECLARE #TimeValue time(7) = '17:52:12.1234567',
#DateValue date = '20211016';
SELECT DATEADD(NANOSECOND,DATEDIFF_BIG(NANOSECOND,'00:00:00', #TimeValue) % 1000000,DATEADD(MILLISECOND, DATEDIFF_BIG(MILLISECOND,'00:00:00', #TimeValue), CONVERT(datetime2(7),#DateValue)));
Finally, yes, you can convert to values to strings, and then to a datetime2 value; this is probably the easiest methiod. You just need to ensure you use style codes:
DECLARE #TimeValue time(7) = '17:52:12.1234567',
#DateValue date = '20211016';
SELECT CONVERT(datetime2(7),CONVERT(varchar(10), #DateValue, 23) + 'T' + CONVERT(varchar(17), #TimeValue, 114),126);
I'm going nuts trying to convert a string type column into date.
The column name is StartDate, which contains a string date format dd/mm/yyyy. The field type is varchar(3000).
I tried the following:
CONVERT(datetime, StartDate, 103)
CAST(CONVERT(VARCHAR(10), StartDate, 110) AS DATE)
CONVERT(DATE, RIGHT(StartDate, 4) + '-' + SUBSTRING(StartDate, 4, 2) + '-' + LEFT(StartDate, 2), 126)
and other similar combinations.
I keep getting "out of range" and "conversion failed" error messages.
Does anyone have a creative solution?
I suspect you have some bogus data. For example
Select try_convert(date, '15/07/2014', 103)
Returns
2014-07-15
If 2012+, I would suggest that you
Select *
From YourTable
Where try_convert(date, StartDate, 103) is null
This will identify your problem areas
I have a query log table (system table), it returns:
After attach the date and time, I need convert:
'20160404105625'
To dateTime type:
2016-04-04 10:56:25.00
You'll need the string in the format "20160404 10:56:25" to be able to convert it to the desired result:
SELECT CONVERT(DATETIME, run_date + ' ' + LEFT(run_time, 2) + ':' + SUBSTRING(run_time, 2, 2) + ':' + RIGHT(2, run_time))
FROM your_table
I'm trying to convert some MS Access queries to T-SQL to use in SSIS (basically converting Access db to SQL server 2008) and I'm having trouble converting an IIF() statement. I tried several approaches and it always resulted in an error.
The query creates a column with dates that are "original Date + 2 years if the condition is met and original Date + 1 if the condition is not met". The first part of the IIF() eliminates the case of the original year being a leap year and so the possibility of generating a non-existing date.
The original IIF() statement is:
IIf((Day(Date)=29 And Month(Date)=2),
IIf(Desc Like "*" & "123" & "*",
DateSerial(Year(Date)+2,Month(Date),Day(Date)-1),
DateSerial(Year(Date)+1,Month(Date),Day(Date)-1)),
IIf(Desc Like "*" & "123" & "*",
DateSerial(Year(Date)+2,Month(Date),Day(Date)),
DateSerial(Year(Date)+1,Month(Date),Day(Date)))) AS Term
So the problem is not only an IIF() statement but also DATESERIAL function. I found the solution for the DATESERIAL() function using CAST() (SQL server 2008 does not have the DATEFROMPARTS() function...).
I tried using CASE() like this:
CASE
WHEN DAY(Date)=29 AND Month(Date)=2 THEN
CASE
WHEN Desc LIKE "%123%" THEN
CAST(CAST(YEAR(Date)+2 AS VARCHAR(4)) + RIGHT('0' + CAST(MONTH(Date) AS VARCHAR(2)), 2) + RIGHT('0' + CAST(DAY(Date)-1 AS VARCHAR(2)), 2) AS DATETIME )
ELSE CAST(CAST(YEAR(Date)+1 AS VARCHAR(4)) + RIGHT('0' + CAST(MONTH(Date) AS VARCHAR(2)), 2) + RIGHT('0' + CAST(DAY(Date)-1 AS VARCHAR(2)), 2) AS DATETIME ) END
ELSE CASE
WHEN Desc LIKE "%123%" THEN
THEN CAST(CAST(YEAR(Date)+2 AS VARCHAR(4)) + RIGHT('0' + CAST(MONTH(Date) AS VARCHAR(2)), 2) + RIGHT('0' + CAST(DAY(Date) AS VARCHAR(2)), 2) AS DATETIME )
ELSE CAST(CAST(YEAR(Date)+1 AS VARCHAR(4)) + RIGHT('0' + CAST(MONTH(Date) AS VARCHAR(2)), 2) + RIGHT('0' + CAST(DAY(Date) AS VARCHAR(2)), 2) AS DATETIME )END END AS Term
I also tried using COAELSCE() but with no better outcome.
I really don't know if I have made some kind of syntax error or where the problem could be.
Thank you in advance for any help.
edit: I'll add error message I'm getting: Incorrect syntax near '...'. The '...' changes as I try different approaches, sometimes its ELSE, THEN etc.
SQL Server's DATEADD may help to simplify things here...
CASE WHEN (<your condition>)
THEN DATEADD(YEAR, 1, [OriginalDate])
ELSE DATEADD(YEAR, 2, [OriginalDate])
END
Should also cope with leap years too.
DateSerial is such a useful function to have around, just create your own.
I got my version from here:
CREATE FUNCTION dbo.DateSerial
(
#year int,
#month int,
#day int
)
RETURNS datetime
AS
BEGIN
DECLARE #date datetime
-- convert date by adding together like yyyymmdd
SET #date = cast(#year * 10000 + 101 AS char(8));
-- Add to date the proper months subtracting 1, since we used 1 as start instead of zero.
SET #date = dateadd(mm , #month - 1 , #date)
-- Add to date the proper days subtracting 1, since we used 1 as start instead of zero.
SET #date = dateadd(dd , #day - 1 , #date);
RETURN #date ;
END;
GO
Here is another way: Date serial in SQL?
Then use the function just as you did in Access.
Edit: just noticed that your outer IIF is to handle leap years. This is not needed when using dateadd().
I'm trying to do a SUM of time values, but the output is rendered as 1900-01-01 05:46:11.740. Note the preceding date part 1900-01-01. I only want the time value.
Below is an example of what I have tried:
DATEADD(MS, SUM(DATEDIFF(MS, '00:00:00.000', R.[Result].value('(/Result/Time/text())[1]', 'datetime'))), '00:00:00.000')
R.[Result].value() is an XML value with format 00:00:00.000
Any idea what I am doing wrong please?
This guy wanted to calculate the sum of the field which has the time datatype.
The Answer on this post had a proper solution which may be helpful:
select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' +
right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from TestTable
Reference : Calculate the SUM of the Column which has Time DataType: