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.
Related
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
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
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]
I have a view where I Select about 100 rows to allow users to easily query data. In this data, I have a field that is sometimes a date and sometimes text. A date or text depends on type. I cast to a date value like so.
SELECT Cast(Value as Date) as column
from Table
Where type = 1
When you then try to run a query against this column, you get a Conversion failed when converting date and/or time from character string. Here is the query.
SELECT Column
From View
WHERE Column BETWEEN '01/01/2015' AND '12/31/2015'
I have another field that is a date and if I replace it in this query, the query works. Likewise the data from the whole table will load. Any ideas are appreciated. Thanks
Basically, I need this Query to work and not give me the error described above.
select cast(value as date)
from Value
where type = 1
and cast(value as date) between '01/01/2015' and '12/31/2015'
My guess is that you have entries in that column that cannot be converted to datetime. You may be able to find them by running
Select * from table where isdate(value) = 0
I have a scenario where I have an int column with the following dates for example:
20131210
20131209
What I want is, I want to convert the above to a date datatype so that I can use it with GETDATE() function.
This is my try but I am getting an error:
SELECT CONVERT(DATETIME, CONVERT(varchar(8), MyColumnName))
FROM MyTable
WHERE DATEADD(day, -2, CONVERT(DATETIME, CONVERT(CHAR(8), MyColumnName))) < GetDate()
This is the error I am getting:
Conversion failed when converting date and/or time from character string.
You have at least one bad date in your column (it could be 99999999 or 20130231 or who knows). This is what happens when you choose the wrong data type. You can identify the bad row(s) using:
SELECT MyColumnName FROM dbo.MyTable
WHERE ISDATE(CONVERT(CHAR(8), MyColumnMame)) = 0;
Then you can fix them or delete them.
Once you do that, you should fix the table. There is absolutely no upside to storing dates as integers, and a whole lot of downsides.
Once you have the date being stored in the correct format, your query is much simpler. And I highly recommend applying functions etc. to the right-hand side of the predicate as opposed to applying it to the column (this kills SQL Server's ability to make efficient use of any index on that column, which you should have if this is a common query pattern).
SELECT MyColumnName
FROM dbo.MyTable
WHERE MyColumnName < DATEADD(DAY, 2, GETDATE());
Try:
CREATE TABLE IntsToDates(
Ints INT
)
INSERT INTO IntsToDates
VALUES (20131210)
, (20131209)
SELECT CAST(CAST(Ints AS VARCHAR(12)) AS DATE)
FROM IntsToDates
I've had a similar problem where I need to convert INT to DATE and needed to cater for values of 0. This case statement did the trick for me
CASE MySourceColumn
WHEN ISDATE(CONVERT(CHAR(8),MySourceColumn)) THEN CAST('19000101' AS DATE)
ELSE CAST(CAST(MySourceColumn AS CHAR) AS DATE)
END
AS MyTargetColumn