SQL Server: combine date column and time column, insert into datetime column - sql-server

I have a database with a date and a time stored separately in datetime columns (not my idea). I need to combine their values to put into another table with a datetime column. As simple as this seems, I just don't seem to be able to do it.
I can get my date value:
cast(sampledate as date) -- returns '2014-11-01'
And my date value:
cast(CollectionTime as time) -- returns '06:46:00.0000000'
I've tried a few different ways of putting them together that look OK.
For example:
concat(cast(sampledate as date) , ' ' , cast(CollectionTime as time)) -- returns '2014-11-05 08:14:00.0000000'
But when I try to insert this into a datetime column, or even just cast it as a datetime value, it doesn't work:
cast(concat(cast(sampledate as date) , ' ' , cast(CollectionTime as time)) as datetime)
-- I get the error 'Conversion failed when converting date and/or time from character string.'
This link warned me against using the FORMAT function, and I've been to some other sites that tell me what NOT to do, but I just can't seem to do this simple thing. Can anyone help? Thanks.
EDIT: Figured it out. This link solved it for older versions of SQL, but not current versions. However, it works fine if you cast to datetime2(0), not datetime.

As I commented above, here is an example where you can add the two datetimes together.
If either column is NOT datetime, simply convert that column to a datetime
Declare #YourTable table (sampledate datetime,CollectionTime datetime)
Insert Into #YourTable values
('2019-06-25 00:00:00','09:09:31')
Select *
,NewDateTime = sampleDate + CollectionTime
From #YourTable
Results
sampledate CollectionTime NewDateTime
2019-06-25 00:00:00.000 1900-01-01 09:09:31.000 2019-06-25 09:09:31.000

Related

convert different string date formats from single column to one form of output in sql server

I have one date columns as varchar datatype which has multiple date formats. I have to convert all different formats into one date format as 'YYYY-MM-DD'.
I am trying to convert it but couldn't make it. Below are different formats available in column.
Input
8/15/2022
15-Aug-22
15/08/2022
Required Output
2022-08-15
Honestly, I think you need to take the pessimistic approach here and assume that, possibly for a lot of your data, you don't know what the value is meant to be. As I stated in the comments, if you have the value '01/12/2021' is that 1 December 2021 or 12 January 2021, how do you know, and more importantly how would SQL Server know? As such, for dates like this you don't know and therefore the value NULL is more appropriate that a guess.
Here I use 3 different formats, an implicit one, and then 2 explicit ones (MM/dd/yyyy and dd/MM/yyyy) Then I check if the MIN and MAX values match (NULL values are ignored for aggregation), and if they do return that value. If they don't then NULL, as what value the date is is ambiguous and therefore intentionally shown as an unknown value (NULL):
You can, if needed, add more styles to the below, but this should be enough for you to work with.
CREATE TABLE dbo.YourTable (ID int IDENTITY(1,1), --I assume you have a unique identifier
StringDate varchar(20));
INSERT INTO dbo.YourTable (StringDate)
VALUES('8/15/2022'), --Must be M/d/yyyy
('15-Aug-22'),
('15/08/2022'), --Must be dd/MM/yyyy
('12/01/2021'); --Could be MM/dd/yyyy or dd/MM/yyyy
GO
SELECT YT.ID,
YT.StringDate,
CASE MAX(V.SomeDate) WHEN MIN(V.SomeDate) THEN MAX(V.SomeDate) END AS DateDate
FROM dbo.YourTable YT
CROSS APPLY (VALUES(TRY_CONVERT(date,YT.StringDate)), --Implicit conversion
(TRY_CONVERT(date,YT.StringDate,101)), --US style MM/dd/yyyy
(TRY_CONVERT(date,YT.StringDate,103)))V(SomeDate) --UK style dd/MM/yyyy
GROUP BY YT.ID,
YT.StringDate;
GO
DROP TABLE dbo.YourTable;
db<>fiddle
You can use a combination of TRY_CONVERT and REPLACE function in a CASE operator to do so.
As an example :
DECLARE #T TABLE(STR_DATE VARCHAR(32));
INSERT INTO #T VALUES
('8/15/2022'),
('15-Aug-22'),
('15/08/2022');
SELECT CASE
WHEN TRY_CONVERT(DATE, STR_DATE, 101) IS NOT NULL
THEN CONVERT(DATE, STR_DATE, 101)
WHEN TRY_CONVERT(DATE, REPLACE(STR_DATE, '-', ' '), 6) IS NOT NULL
THEN CONVERT(DATE, REPLACE(STR_DATE, '-', ' '), 6)
WHEN TRY_CONVERT(DATE, STR_DATE, 103) IS NOT NULL
THEN CONVERT(DATE, STR_DATE, 103)
END
FROM #T

TSQL : Conversion failed when converting date and/or time from character string

I had a query that was working but after importing again one table I see the following problem when converting a Varchar into DateTime.
I have the following problem when running the following query:
select FORMAT(convert (datetime,date) , 'ddMMyyyy') from kat.[dbo].[myTable]
If I try the following I see the same problem:
SELECT convert(datetime, date, 126) from kat.[dbo].[myTable]
The dates that I have in the main table follow the same format:
2017-09-01
EDit with Data Screenshot for the Format:
MAny thanks in advance,
Kat
The dates that I have in the main table follow the same format:
2017-09-01
There are some stings in your table that have different format.
Try to catch them with this code:
select *
from kat.[dbo].[myTable]
where dt not like '[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]';
In future, don't store datetime values as strings, use datetime/date.
UPDATE
So it's not true that your strings are like '2017-09-01'
Here is my example with your date:
declare #t table (dt varchar(20));
insert into #t values ('2017-09-01');
select *
from #t
where dt not like '[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]';
My code returns no rows because '2017-09-01' reflects the format you inicated, and if it returns all rows in your case, the format is different.
I actually think strings cannot be converted directly to dates (at least not when you use CAST)... Why not convert the string to an int first?
Assuming your column is named [Date], I would stick with:
SELECT
cast(DATEADD(DAY, cast([Date] as int), -2) as date) as [Date]
FROM kat.[dbo].[myTable]
If you have a different column name, here is the template:
SELECT
cast(DATEADD(DAY, cast([MyColumnName] as int), -2) as date) as [MyColumnName]
FROM kat.[dbo].[myTable]
Alternatively, I've also updated your code using CONVERT (which honestly I rarely every use so it could be wrong)
SELECT convert(datetime, convert(int, [Date]), 126) from kat.[dbo].[myTable]

Convert to mm/dd/yyyy and select max value

Using SQL Server 2014, I have a date field named LAST_BASELINE_UPDATE_DATE that is stored as datetime.
I used the CONVERT function to convert to mm/dd/yyyy:
convert(date,LAST_BASELINE_UPDATE_DATE,101) as BASELINE_UPDATE_DATE
What I want to be able to do is then select the MAX value of BASELINE_UPDATE_DATE without creating a table. Is this even possible?
It's a little unclear from your post what your data is and what you're trying to get out. Here are a couple solutions, hopefully one of which is applicable
Assuming you want your result as a string formatted mm/dd/yyyy you can do this
select convert(varchar(10), max(LAST_BASELINE_UPDATE_DATE), 101))
from YourTable
If you just need it as a date, just do
select max(LAST_BASELINE_UPDATE_DATE)
from YourTable
if LAST_BASELINE_UPDATE_DATE is already a string (formatted mm/dd/yyyy) and you want it as a date,
select max(convert(date, LAST_BASELINE_UPDATE_DATE, 101))
from YourTable
I think you are complicating this. Just do the conversion on the max datetime values.
declare #table table (LAST_BASELINE_UPDATE_DATE datetime)
insert into #table
values
('20160701 12:21'),
('20160705 03:21'),
('20160401 19:21'),
('20161201 04:21')
select
convert(varchar(10),max(LAST_BASELINE_UPDATE_DATE),101)
from
#table
This method converts your single returned row, which is the max() value of your datetime columns, as opposed to converting every row and then finding the max value.

Convert and sort varchar Date dd-MMM-yyyy

I'm using a table that has the date as varchar. example dateformat:
17-Jun-2015
I have tried the following ways to convert and sort the date(dd-MMM-yyyy) to dateTime.
SELECT date, name, author
FROM sometable
ORDER BY CONVERT(DATETIME, date, 106) DESC
I have also tried converting the date in the select statement. doesn't work. The error is
Conversion failed when converting date and/or time from character string.
The conversion types through some similar questions but I have not found any solutions to the format I have. Is there some way of selecting the delimiter between the day month and year??
I also had a browse through this link which has the formats for datetime formats. 106 was the closest to my varchar date. Only my date in the table has '-' between day month and year.
https://msdn.microsoft.com/en-us/library/ms187928.aspx
Appreciate any help.
It should be absolutely fine to use 106 to convert your date format.
But I guess your table contains some of the invalid values in the column causes the error, try to spot them out by TRY_CONVERT:
SELECT date, name, author, TRY_CONVERT(datetime, date, 106) AS convertresult
FROM sometable
WHERE TRY_CONVERT(datetime, date, 106) IS NULL AND date IS NOT NULL
I would use date style 113 to convert to datetime format like this:
DECLARE #date VARCHAR(20) = '17-Jun-2015';
SELECT CONVERT(VARCHAR(20),CAST(#date AS DATETIME),113)

Compare 2 DateTime values in a WHERE clause

I have a very simple query. (I'm working in SQL Server 2008.) I'm trying to select all records from a view where their ModifiedOn column is greater than a specified date. The ModifiedOn column is a datetime format. So, I have:
DECLARE #date1 AS datetime = '2013-07-31 24.59.59.999'
SELECT
some_column
FROM dbo.some_view
WHERE ModifiedOn > #date1
SQL is throwing the following error, though:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. Why is SQL thinking that one of my dates is a varchar, when I know that both of them are datetime formats? How do I fix it?
Datetime variable expects data to be in format of
YYYY-MM-DD HH:MM:SS.mmm
In your case you are trying to assign a value which is not a valid time. HH.MM.SS.mmm
Secondly a clock never strikes 24:00:00 it goes from 23:59:59.999 to 00:00:00.001.
Also in your case rather than juggling with seconds and milliseconds. just use date value and use the ANSI standard YYYYMMDD which is also sargable.
You could have written your above query something like
SELECT some_column
FROM dbo.some_view
WHERE ModifiedOn >= '20130801'

Resources