Convert varchar to datefield in SQL Server - sql-server

I am aware that this is a very common and have tried using the solutions suggested on similar questions. However, I cant seem to make it work.
I have a column which contains dates, but it is of varchar datatype.
The data looks like this:
startdate
-----------
15/01/2007
29/06/1998
07/12/2001
and so on..
I tried the following command
try_convert(datetime, startdate) as 'startdate'
But it returns a lot of NULLs even when there is a date populated in the original column.
Can someone please help?

The try_convert method accepts three arguments: Data type, Expression, and Style.
You need to use the Style argument:
try_convert(datetime, startdate, 103) as 'startdate' -- 103 is dd/MM/yyyy
(a list of supported styles can be found here)
Also, You should store date values as Date, not as varchar.
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type

Related

Cast as Date Only

My goal is to display this
02/28/19 63
from this. (date_birth is datetime in DB)
1963-02-28 00:00:00.000
I used this SQL query code
FORMAT(date_birth,'MM/dd/19 yy')
but my teacher wanted it in a cast so I did this
CAST(date_birth as date) as date_birth
How can i format the above date through cast?
Since date_birth is already a DateTime column in the DB, you can chain the function calls and call them together.
Something like this: FORMAT(CAST(date_birth as DATE),'MM/dd/19 yy')
Please note that the order matters here - also, if date_birth is a VARCHAR in the DB, then this might not work as the contents of the string could be different from something a Date could accept.
For info: https://www.sqlservertutorial.net/sql-server-system-functions/convert-datetime-to-date/

Varchar(255) as MM/DD/YYYY HH:MM to Datetime format - SQL Server

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

T SQL Conversion failed when converting date and/or time from character string from VARCHAR(MAX)

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.

Date conversion in a XML column in SQL Server

How do I convert the below mentioned XML code date format.
<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>
If you're accessing your XML content with the built-in XQuery functionality, you can just use the .value() method and define the output datatype to be a DATETIME2(3) type - no special treatment necessary:
DECLARE #InputTbl TABLE (ID INT NOT NULL, XmlContent XML)
INSERT INTO #InputTbl (ID, XmlContent)
VALUES (1, '<Root>
<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>
</Root>');
SELECT
StartDate = XC.value('(StartDate)[1]', 'datetime2(3)'),
EndDate = XC.value('(EndDate)[1]', 'datetime2(3)')
FROM
#InputTbl
CROSS APPLY
XmlContent.nodes('/Root') AS XT(XC)
This returns this output:
There are several correct answers, but I've got the feeling, that these answers don't hit your actual issue:
In my table there is a xml column, and that xml column contains somuch data including date, And i want to update those dates to date format like '2/28/2017' now the date format is like '2012-04-26T00:00:00'
If I got you correctly you want to change the stored dates within your XML to another format, correct?
Simple answer: Don't!
ISO8601 is the standard format for date/time values within XML. The format you would like more 2/28/2017 is culture related and could lead to errors, or even worse!, to wrong values, if day and month both are below 13: 04/05/2017 can be taken as 4th of May or as 5th of April. You should never rely on culture settings!
XML is not meant to be human readable. Or in better words: It is meant to be human readable for technical people only... It is a standardizes string representation of structured, complex documents. The format of values should not bother you! Use an appropriate editor for the presentation.
This might be work
declare #date ='2015-12-24T00:00:00 2015-12-29T15:39:20'
SELECT CONVERT(date, Left(#date,10)) as NewDate
This may help you
DECLARE #X XML ='<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>'
SELECT #X.value('/StartDate[1]','DATETIME') AS START_DTE
,#X.value('/EndDate[1]','DATETIME') AS END_DTE
+-------------------------+-------------------------+
| START_DTE | END_DTE |
+-------------------------+-------------------------+
| 2015-12-24 00:00:00.000 | 2015-12-29 15:39:20.000 |
+-------------------------+-------------------------+
Update: From comments
The Datatime format in XML follows the ISO8601 standards. And you are thinking to format it native SQL format, which is not correct that you are treating XML like normal text data. The data present in XML format is correct. And If you want you can convert it to native SQL as above mentioned.
There is a good info at Wikipedia ISO 8601(Combined date and time representations)
on how the XML hold date time data.
A single point in time can be represented by concatenating a complete
date expression, the letter T as a delimiter, and a valid time
expression. For example, "2007-04-05T14:30".

Display a Date that is stored in SQL Server as Char yyyy-mm-dd as mm-dd-yyyy

I have a char column that stores dates as yyyy-mm-dd. I need to display these dates as mm-dd-yyyy.
Thanks in advance.
The root of your problem is because you are using the wrong datatype. Dates should stored as dates. Anything else is nothing but a pain to work with. To get your formatting you will first have to convert your string to a date so
you can format it.
Here is an example.
select convert(date, YourDateColumn, 101)
You can read more about convert here. https://msdn.microsoft.com/en-us/library/ms187928.aspx
If 2012+ you could try
Select Format(GetDate(),'MM-dd-yyyy')
Returns
08-03-2016
To convert the string
Select Format(cast('2016-08-03' as date),'MM-dd-yyyy')
DECLARE #Date varchar(12)='2012-01-29'
SELECT FORMAT(CONVERT(datetime,LEFT(#Date,4) + SUBSTRING(#Date,6,2) + SUBSTRING(#Date,9,2)), 'MM-dd-yyyy', 'en-US' ) AS Result
This is a little bit heavy on processing, but it works.
This answer also assumes that ALL values in the date text column are formatted as YYYY-MM-DD. If you have any values that aren't formatted that way as strings, then you will run into problems.
Obviously you will need to replace the #Date variable with the name of your date text column. I wanted to provide an example you can run easily to check the answer.

Resources