running :
SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
will result :
Jan 4 2012 1:25PM
Ive been knowing this for years.
However , yesterday, while I was driving , I thought to my self :
Hey! I gave him the format of 103 which is for datetime format ,
But I didnt actually TOLD the convert that Im passing also a datetime
object ! ( e.g. getdate()))
So ive tried :
SELECT CONVERT(VARCHAR(20), 'lalala', 100)
And the result was :
lalala
so , now Im trying to convert 'lalala' to string via datetime format (103).
which is ( by logic) should give me exception.
but it is not.
Any reasonable explanation ?
CONVERT takes into account both the target type and the expression's type to see whether the third argument should be considered. If you are converting a datetime to a string or the other way round, the third argument is considered. In your example, a string is converted to a string and so the third argument is ignored.
Consider this:
SELECT 1, CONVERT(datetime, '03/01/2011', 103)
SELECT 2, CONVERT(datetime, '03/01/2011', 101)
SELECT 3, CONVERT(varchar, '03/01/2011', 103)
SELECT 4, CONVERT(varchar, '03/01/2011', 101)
Here are the results:
--- -----------------------
1 2011-01-03 00:00:00.000
--- -----------------------
2 2011-03-01 00:00:00.000
--- ------------------------------
3 03/01/2011
--- ------------------------------
4 03/01/2011
As you can see, the last two ‘conversions’ didn't change anything, because both the source and the target type were varchar, even though the expression did look like a date/datetime.
Reference:
CAST and CONVERT (Transact-SQL)
The convert function only uses the 3rd parameter (style) if the 2nd one (data_to_be_converted) is datetime.
If it's already varchar it returns the value and don't make anything.
The MSDN documentation for CONVERT says that the style parameter is interpreted based on the type of the value passed - so I guess it inspects the value and can tell which type it is.
For example, notice that a style of '1' means "mm/dd/yy" for datetimes and "Always 8 digits. Always use in scientific notation" for float values.
Related
I can't make out from the documentation why SQL Server parses a text in a format other than the specified style.
Regardless of whether I provide text in the expected format:
SELECT CONVERT(DATETIME, N'20150601', 112)
or incorrect format (for style 113):
SELECT CONVERT(DATETIME, N'20150601', 113)
The results are the same: 2015-06-01 00:00:00.000 I would expect the latter to fail to convert the date (correctly).
What rules does it employ when trying to convert a VARCHAR to DATETIME? I.e. why does the latter (incorrect format style) still correctly parse the date?
EDIT: It seems I've not been clear enough. Style 113 should expect dd mon yyyy hh:mi:ss:mmm(24h) but it happily converts values in the format yyyymmdd for some reason.
Because the date is in a canonical format ie(20150101). The database engine falls over it implicitly. This is a compatibility feature.
If you swapped these around to UK or US date formats, you would receive conversion errors, because they cannot be implicitly converted.
EDIT: You could actually tell it to convert it to a pig, and it would still implicitly convert it to date time:
select convert(datetime,'20150425',99999999)
select convert(datetime,'20150425',100)
select convert(datetime,'20150425',113)
select convert(datetime,'20150425',010)
select convert(datetime,'20150425',8008135)
select convert(datetime,'20150425',000)
And proof of concept that this is a compatibility feature:
select convert(datetime2,'20150425',99999999)
Although you can still implicitly convert datetime2 objects, but the style must be in the scope of the conversion chart.
Reason why is the date N'20150601' converted to valid datetime is because of fact that literal N'20150601' is universal notation of datetime in SQL Server. That means, if you state datetime value in format N'yyyymmdd', SQL Server know that it is universal datetime format and know how to read it, in which order.
You should convert to varchar type in order to apply those formats:
SELECT CONVERT(varchar(100), CAST('20150601' as date), 113)
OK, you are converting datetime to datetime. What did you expect? In order to apply formats you should convert to varchar and you have to have date or time type as second parameter.
I currently have dates stored in a general attribute field in the database as a string.
They are all stored in the format DD/MM/YYYY for example 01/01/2000
I am able to convert them them to datetime successfully by using the following in my select statement. For example CONVERT(DATETIME, attribute.field_value, 103) where attribute.field_value contains a date.
The SELECT statement works fine and returns the whole table with them correctly.
I can also return a column with todays date in the same format as follows CAST(getdate() AS datetime)
The problem occurs when I try to compare, now I only want to return everything that is newer than today in pseudo code that would dateNewerThanToday > dateToday
Therefore I have tried
WHERE CONVERT(DATETIME, attribute.field_value, 103) > CAST(getdate() AS datetime)
this gives me the error
Conversion failed when converting datetime from character string.
I have tried a multitude of cast/converts to get it to work. I have also wrapped by select so I am only doing it on dataset with the correct data.
Any help would be super useful! Many thanks in advance!!
A couple of things ..
You do not need to convert to GETDATE() to DATETIME data type as it already returns datetime data type.
Instead of CONVERT(DATETIME, attribute.field_value, 103)
use
CONVERT(DATETIME, attribute.field_value) or CAST(attribute.field_value AS DATETIME)
Add a where clause in your select to get only valid DATETIME values. something like
WHERE ISDATE(attribute.field_value) = 1
This will filter out any values which appears to be a date value but sql server doesnt see them as valid date values.
Important Not
Use appropriate data types. If this column is storing date values why not use the DATE or DATETIME data types.
I ran into this exact problem.
Values from a VARCHAR(50) column returned in the SELECT could be cast as date without issue. However when cast in a comparison in the WHERE clause the error occurred.
Of note, the error only occurred when I had other restrictions in the WHERE clause.
When I added ISDATE() to the WHERE clause, the error no longer occurred.
e.g. Shortened example of what worked:
SELECT CONVERT(DATE, mat.myAttributeColumn), mdct.myDateComparisonColumn
FROM myAttributeTable mat
JOIN myDateComparisonTable mdct ON mdct.key = mat.key
WHERE ISDATE(mat.myAttributeColumn) = 1
and mdct.myDateComparisonColumn < convert(DATE, mat.myAttributeColumn)
I have a varchar(200) column called Submit_Date and I am trying to convert it to MM/DD/YYYY format. When I do that I get the following error:
Msg 242, Level 16, State 3, Line 1The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Sample Data of the table is:
Submit_Date
-----------------------
27-09-2013 16:15:00 CST
30-09-2013 16:30:24 CST
27-09-2013 10:03:46 CST
I tried the following:
Select Convert(datetime,Submit_date,101) from dbo.Tickets
You've committed about 15 cardinal sins about date/time here. First, the quick answer:
DECLARE #x VARCHAR(200);
SELECT #x = '27-09-2013 16:15:00 CST'
SELECT CONVERT(CHAR(10),CONVERT(DATETIME,LEFT(#x,10),105),101);
Next:
Why on earth are you storing date/time data in a varchar(200) column? You are aware that anyone can insert values like '09-27-2013' or '465-32-207floob' in there, right? If you need time zone information you can look at the DATETIMEOFFSET data type (but note that it is not DST-aware).
Why are you storing a regional format like dd-mm-yyyy? If the first value were 07-11-2013 I'd have to guess if you meant July 11 or November 7. If you're not going to do it right and use a proper date/time data type, why use a string format that makes people guess? You are much better off with a format that is unambiguous, such as yyyy-mm-ddThh:mm:ssZ.
Similarly, why are you outputting a different regional format like mm/dd/yyyy? If you output '05/06/2013' are you 100% confident that everyone in your audience will know you meant May 6 and not June 5? Your output should be unambiguous as well. If you absolutely must format in some regional and ambiguous format, use the string formatting capabilities of your client. For example, C# has .ToString() and .Format() which are much more powerful and efficient in presenting dates with string formats that T-SQL will ever be.
try the following SQL query to achieve the expected result:
SELECT convert(varchar, convert(date, '27-09-2013 16:15:00', 105), 101)
I have a table called SF_Data and there is a column called IN_Date, ID the data looks like:
ID IN_Date
1 9/8/2010
2 26/04/2011
3 20/09/2010
The datatatype of IN_Date is varchar(50).
I am trying to convert the IN_Date to mm/dd/yyyy format. I tried doing this:
Select convert(varchar,IN_Date,103) From dbo.SF_Data
But still the format doesn't change. Can anyone tell me where I am going wrong
You need a convert to fix the data (to the correct datatype) before formatting...
Select
convert(varchar,
convert(date, IN_Date, 103),
101)
from dbo.SF_Data
The 3rd parameter to convert has no meaning when converting from varchar to varchar. So per #marc_s' comment, you'd have to convert the varchar to a datetime using the 103 format, and then from datetime to varchar specifying the 101 format:
Select convert(varchar(12),convert(datetime,IN_Date,103),101) From dbo.SF_Data
For example:
select convert(varchar(12),convert(datetime,'31/12/2001',103),101)
prints 12/31/2001.
See MSDN.
I'm trying to figure out an elegant way to get a date from a text column that has data like this "YYYYMMDD"...so we might see "20060508" as a value in the column, which I would like to be able to return from a query as a date (May 8, 2006).
I'm sure I can hack something together given enough time, but the approaches I'm thinking of seem pretty kludgy, and I suspect there's a way this can be elegantly done in a single query.
Any suggestions?
This is already a valid date - ISO-8601 format - just use:
SELECT CAST('20060508' AS DATETIME)
or alternatively:
SELECT CONVERT(DATETIME, '20060508', 112)
and that should do just fine!
In order to get your "May 08, 2006" display, do another convert into varchar, using the date convert style 107:
SELECT CONVERT(VARCHAR(25), CAST('2006-05-08' AS DATETIME), 107)
See here for more information on casting & converting in MS SQL
select cast('20060508' as datetime) AS MyDate
gives you this result...
MyDate
-----------------------
2006-05-08 00:00:00.000
See here for more information on casting & converting in MS SQL.
If you're trying to achieve a specific format (May 8, 2006) - you should consider just returning the column as a datetime value, and letting whatever is going to display that value to the end user (website, client app, report, etc) do the formatting. If you format it at the query, you'll be returning a string, which will make it harder to swap out formats from your front end in the future. If you want to do it in SQL - check out format 107 in the link above.
No sweat, just CONVERT it. Style "112", or ISO would handle your example case.
SELECT CONVERT(datetime,'20060508',112)
returns
----------------------- 2006-05-08 00:00:00.000
(1 row(s) affected)
try:
SELECT REPLACE(CONVERT(varchar(30),CONVERT(datetime, '20060508'),107),' 0',' ')
output:
-------------------
May 8, 2006
(1 row(s) affected)