I have a varchar column header (Prod_time) in the [YYYYmmdd hhmmss] format that I am trying to convert to datetime. I need to be able to pull data from a certain number of days, and I would like to be able to convert the varchar to datetime to facilitate this.
Is there a way to convert varchar to datetime? No special formatting of the datetime needed, only a data type conversion.
You need to force a couple characters in here so that the convert function knows how to deal with this. We can use STUFF for this pretty easily. This works given the provided string format.
declare #SomeChar varchar(20) = '20170216 100903'
select CONVERT(datetime, STUFF(STUFF(#SomeChar, 12, 0, ':'), 15, 0, ':'))
If at all possible you should consider converting the datatype to a datetime. It eliminates this kind of hassle and also prevents invalid values.
Related
I know there are a million of these date conversion questions, but I can't find the specific one to solve my problem.
I have a table with a column [Date] that contains data that is formatted as MM/DD/YYYY HH:MM, but is stored as a varchar.
[Date] (varchar(255),null)
12/22/2017 0:34
12/21/2017 21:33
12/21/2017 21:17
...
I need to run a query and filter by date range, so I need to figure out how to convert to a usable datetime format.
I've tried
WHERE CONVERT(VARCHAR(255), CAST([Date] AS DATETIME), 121) between #beg1 and #end1
But get the error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I've tried several other answers, but none were quite formatted the same as my data so the conversions didn't work.
Any help would be greatly appreciated
As many of us have mentioned, to real solution is fix the data type, which means altering the database.
First, to fix the data, you need to change the format to an ISO format, specifically here we're going to do with the ISO8601 format (yyyy-mm-ddThh:mi:ss.mmm). This will require a TRY_CONVERT and CONVERT (the first to change the data to a smalldatetime and the second to the formatted varchar):
UPDATE dbo.YourTable
SET YourDate = CONVERT(varchar(20),TRY_CONVERT(smalldatetime, YourDate, 101), 126);
Now we can alter the data type (to a smalldatetime as your data is accurate to a minute:
ALTER TABLE dbo.YourTable ALTER COLUMN YourDate smalldatetime NULL;
If you "must" leave it at a varchar (this is a bad idea, as your data has so many problems is so), then you need to use TRY_CONVERT in the WHERE, with the correct style code:
WHERE TRY_CONVERT(smalldatetime, YourDate, 101)
This is, however, a really bad idea as your data is severely flawed. For example, according to your data, the "date" '12/22/2017 0:34' is after today ('09/30/2020 21:25'), not before.
The code as you wrote it works fine. You probably have a badly formatted record or record where it is not in a date format. Try code like this to find those records. Any columns with a "NULL" value are ones where the try_cast could not succeed. These are the ones blowing up your query.
You can then choose to correct these values or simply exclude them from your query.
SELECT
[DateText], try_cast([DateText] AS Datetime) FROM Dates
I'm using SQL Server 2014. I have a date stored as varchar(MAX) in the format of:
2019-02-18
However, I want it in the British format dd/mm/yyyy (103).
This is my SQL:
SELECT CONVERT(DATE, DateField, 103) AS "JobStartDate"
FROM tblTest
However, I keep getting this error:
Conversion failed when converting date and/or time from character string.
What am I missing?
Update: The date is initially stored as varchar max as it is coming from a 3rd party system. I have no control over this and I completly understand this is the wrong format, but this is what I have been given.
I have a date stored as varchar(MAX)
There's your problem right there.
Not only you are using the wrong data type to store dates, you are also using max which is a known performance killer.
The solution to the problem is to alter the table and store dates in a Date data type - but first, you must look up all the objects that depends on that column and make sure they will not break or change them as well.
Assuming this can't be done, or as a temporary workaround, you must first convert the data you have to Date, and then convert it back to a string representation of that date using the 103 style to get dd/mm/yyyy.
Since yyyy-mm-dd string format is not culture dependent with the date data type, you can simply do this:
SELECT CONVERT(char(10), TRY_CAST(DateField As Date), 103) As [JobStartDate]
FROM tblTest
Note I've used try_cast and not cast since the database can't stop you from storing values that can't be converted to dates in that column.
You want to format the DateField column and not convert it to date.
So first convert it to DATE and then apply the format:
SELECT FORMAT(CONVERT(DATE, DateField, 21), 'dd/MM/yyyy') AS JobStartDate
See the demo.
Below is my table structure:
DECLARE #FinalTable TABLE
(
[BranchID] BIGINT NULL,
[BranchName] NVARCHAR(MAX) NULL,
[Date] DATETIME NULL
)
My MSSQLSERVER is too crazy. It is saving the datetime in MMDDYYYY format, not knowing I required SELECT statement output in DDMMYYYY format. I am tired of using that CONVERT() and CAST() functions each and every time to in SELECT statement.
Is there any way to declare table column with my datetime format ( i.e. DDMMYYYY) so that I don't need to use CONVERT() or CAST() functions every time.
No, it's not. There is no formatting information at all associated with the field.
The value is not formatted by the database, it's returned only as a point in time. Formatting that value into it's textual representation is done by the applcation that is getting the data from the database.
So, there is nothing that you can do in the database to change how the date/datetime value is formatted, you have to change that where the data is displayed.
Date Time gets stored in database with the default format based on selected default language for the user. However you can manipulate the format when fetching the date time.
Following is the way to fetch the data with different defined formats:
All Formats for DateTime
But, if you still want to store the Date-Time of your own choice format then you have to create a column with Varchar DataType and later convert into date when fetching it (Not recommended)
Convert(datetime, Expression, FormatStyle)
For more information View the following answers:
Answer1
Answer2
I am importing a text column into a SQL Server 2008 database.
I have a field 'carcassdate' in the following format
'11/05/2017 9:18:46 a.m.'
'10/05/2017 1:08:27 p.m.'
etc. How can I convert this into a proper SQL Server 2008 datetime (24 hour) column please?
I can't seem to find a proper solution for this.
My desired result is
'11/05/2017 9:18:46 a.m.' converted to 2017-05-11 09:18:46.000
'10/05/2017 1:08:27 p.m.' converted to 2017-05-10 13:08:27.000
Thanks in advance.
What I have tried so far:
strip the date part of the column
select convert(date, convert(varchar(10),carcass_date)) as carcassdate
That's the easy part..But I'm struggling with the time part.
Thanks for your help in advance.
The issue is with the periods in the string. By removing them, you can cast the string as a datetime. e.g.:
SELECT CAST(REPLACE(carcass_date, '.', '') AS DATETIME)
When it comes to date conversion, I suggest that you always be explicit.
Any kind of programming that is not explicit about date formats invites bugs.
I suggest you Never use cast as there is no explicit format. Even though it always assumes ISO format, I've never found any info about how it decides other formats (including your which is not ISO)
Never use convert without a format number.
I suggest you instead use convert with a format number. On my system, this returns two different dates. Cast returns the wrong one.
DECLARE #D AS VARCHAR(100) = '05/11/2017 9:18:46 a.m.'
SELECT CONVERT(DATETIME, REPLACE(#D, '.', ''), 103) as converted
SELECT CAST(REPLACE(#D, '.', '') AS DATETIME) as casted
Number 103 is defined as dd/mm/yyyy format. At least this way you have some degree of self documentation - that's the format you expect
Later versions of SQL have parse but it uses cultures, not format strings.
Perhaps read this
https://www.simple-talk.com/sql/t-sql-programming/how-to-get-sql-server-dates-and-times-horribly-wrong/
There's also a non-decisive discussion here:
datetime Cast or Convert?
I have a VARCHAR that holds datetime data in the following format:
15/04/2014 16:05
I need to convert this to datetime (with the exact format as before) but get an out of range error on the conversion:
CONVERT(DATETIME, #endDate, 108)
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
Could any advise the best way to successfully convert? Bear in mind i cannot change the source format and eventually need to compare the date to see if it is past the present day.
I think you want to use 103 instead of 108 for the final parameter.
Please use date constant values that are language/country independent
-- Independent constant (natural date)
DECLARE #END_DTE VARCHAR(20) = '20140415 16:05'
-- Show the result
SELECT CONVERT(DATETIME, #END_DTE, 108) AS FORMAT_DTE