Convert varchar value to datetime in SQL Server 2012 - sql

In my import table I have the following column defined:
LFZ_begin VARCHAR(50) NULL
Now when I try to define the column in a view as DATETIME and call the view in SSMS, I get the following error message:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
In my view the column is defined as follows:
CONVERT(VARCHAR(50), CONVERT(DATETIME, LFZ_begin, 120)) AS LFZ_begin,
I need to expect the result value like that: 2020-09-04 00:00:0000
Does anyone have an idea for this issue?

You should fix your data model and never store date/time values as strings. In the meantime you can fix the view using try_ functions:
TRY_CONVERT(VARCHAR(50), TRY_CONVERT(DATETIME, LFZ_begin, 120)) AS LFZ_begin,
Note: This will eliminate the error on invalid formatted columns. Whether it ever returns a valid value depends on the data -- and you have shown no sample data so there is no way to suggest a solution to whatever the underlying problem is.

Related

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

I'm trying to convert a varchar column to date or datetime but I don't understand why it's not possible it should work and I don't see any kind of error.
The column values is 31-07-2017 and the type is Varchar(250). I tried convert and cast and I get the same error:
Conversion failed when converting date and/or time from character string.
Does anyone have any idea on why it's like this?
The conversion error is because your session setting is other than DATEFORMAT dmy or varchar values do not conform to DMY format.
For the latter case, run the query below to identify problem values:
SELECT YourDateColumn AS InvalidDate
FROM dbo.YourTable
WHERE
YourDateColumn IS NOT NULL
AND TRY_CONVERT(date, YourDateColumn, 103) IS NULL;
As #TimBiegeleisen mentioned in a comment, it is best to choose the most appropriate column type (date in this case) for the data to be stored. Not only will this avoid errors like this, it will improve performance and better ensure data integrity.
I found the issue, it's a very very stupid mistake, there was one column with a text format I couldn't see it because I checked with length, but the SQL gives max length so I used group by and manually check dates until I found one column that's not correct in 1 m account records

How do I convert a string of format dd/mm/yy into datetime in SQL Server 2008?

I have table named PTBV with two columns: Dateptbv varchar(50) and [Column 1] varchar(50).
I'm trying to use the CONVERT() function to get actual datetime values from the string data stored in the Dateptbv column.
Here are examples of the data in that column:
"10/01/13"
"11/01/13"
"14/01/13"
"15/01/13"
"16/01/13"
"17/01/13"
"18/01/13"
"21/01/13"
"22/01/13"
"24/01/13"
"25/01/13"
"28/01/13"
"29/01/13"
"30/01/13"
"01/02/13"
"04/02/13"
Note that the quotation marks in this sample are part of the data and are stored in the column. Otherwise, data is stored in dd/mm/yy format.
Unfortunately, every date style I've tried has resulted in an error message. How can I convert this data into DateTime values?
If I understand your picture correctly, your column Dateptbv is VARCHAR(50) and stores the date as yy/mm/dd wrapped in " characters. First of all: Change this, if ever possible!. Try to store values in appropriately typed columns!
Try
SELECT CONVERT(DATE,SUBSTRING(Dateptbv,2,8)),3) --3 for dd/mm/yy
Read this link to find more details about the abilities of CONVERT.
Try the below script
SELECT CAST(SUBSTRING(Dateptbv,2,8) AS DATE)
FROM PTBV

Finding row causing error in type conversion in SQL Server

I am trying to cast a column as smalldatetime from varchar. There are some rows containing errors, how can I find them?
SELECT
PA.EAR_TAG
,ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE) as HB_Date
,Y.[DATE OF MOVEMENT] as Y_Date
,DATEDIFF(DAY, ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE), cast(Y.[DATE OF MOVEMENT] as smalldatetime))
FROM
DairyTelomere.dbo.PROJECT_ANIMALS AS PA
LEFT JOIN
Langhill.dbo.YOUNG_STOCK_BULL AS B ON Pa.EAR_TAG = B.EAR_TAG
LEFT JOIN
Langhill.dbo.YOUNG_STOCK_HEIFER AS H ON PA.EAR_TAG = H.EAR_TAG
LEFT JOIN
DairyTelomere.dbo.Young_Stock_culls AS Y ON PA.EAR_TAG = Y.Ear_Tag
The error I get is:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.
I know that if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions).
Any ideas will be greatly appreciated.
you can use the isdate to get a list of all the ones that are not converting for you. You dont need to change the column type to use this so i am confused by your statement
if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions)
Will help more if you can clarify but this query should get you a list of rows that have bad date values.
select table.date_as_varchar
from table
where isdate(table.date_as_varchar) = 0
adding to #workabyte answer you can also try using TRY_PARSE, TRY_CAST OR TRY_CONVERT, all of them return NULL if the conversion failed, that way you can know wich rows caused the error.
TRY_PARSE
as the documentation says:
Use TRY_PARSE only for converting from string to date/time and number
types. For general type conversions, continue to use CAST or CONVERT.
Keep in mind that there is a certain performance overhead in parsing
the string value.
Usage example:
SELECT TRY_PARSE(your_date AS DATETIME USING 'es-ES') as date
FROM your_table
es-ES is a culture parameter,different culture paramaters yield different results in your conversions, you can find the full list of parameters in the documentation
TRY_CONVERT
as the documentation says:
TRY_CONVERT takes the value passed to it and tries to convert it to
the specified data_type. If the cast succeeds, TRY_CONVERT returns the
value as the specified data_type; if an error occurs, null is
returned. However if you request a conversion that is explicitly not
permitted, then TRY_CONVERT fails with an error.
Usage example:
SELECT TRY_CONVERT(DATETIME,your_date,103) as date
FROM your_table
The 103 being the style/format of the date you are converting, here you can find a list of the formats avaliable
TRY_CAST
as the documentation says:
TRY_CAST takes the value passed to it and tries to convert it to the
specified data_type. If the cast succeeds, TRY_CAST returns the value
as the specified data_type; if an error occurs, null is returned.
However if you request a conversion that is explicitly not permitted,
then TRY_CAST fails with an error.
Usage example:
SELECT TRY_CAST(your_date AS DATETIME) as date
FROM your_table

Convert from one date style to another

So I have a column in a table that is of type DateTime and are in this style '2013-10-15 11:39:59.137' (yyyy-mm-dd hh:mm:ss:mmm). I am trying to convert to this format (dd/mm/yyyy) '15/10/2013'. I have tried things like this CONVERT(DATETIME,[MyColumnName],103) 103 being the style that I want, but this just displays the exact same thing. I have also tried converting to nvarchar(50) and then converting to datetime with my desired style but I then get this error 'The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.', I am unsure of what this means. Is there anyway in which it is possible to change the style of a date.
If the result is a datetime type again, it show's up with the default representation. If you use varchar as representation it shows up. Here an example:
select CONVERT(varchar(10),getdate(),103)
may this explains it
declare #a varchar(10)
select #a=CONVERT(varchar(10),getdate(),103)
print #a
select convert(datetime,#a,103) as 'Datetime', CONVERT(varchar(10),convert(datetime,#a,103),103) as Text
A DateTime will always be displayed as such.
If you want to change the way it is displayed you need to convert it to VARCHAR:
CONVERT(VARCHAR(10),[MyColumnName],103)
Now, this is for display reasons. If you need to convert back to datetime, you need to provide once more the format:
CONVERT(DATETIME,CONVERT(VARCHAR(10),GETDATE(),103),103)

Update table Error Using Convert Function In SQL Server 2005

I have a table with two columns, all of them are datetime value
Such as, Column A with value ‘07/09/2012 14:13:34’
Now, I want to update column A to yyyymmdd by statement
Update Change_Date
SET A = CONVERT(VARCHAR(8),A,112)
It shows succsessful message but with no effect (no update value to 20120907) in my table Change_Date.
Any help will be greated, thank you!
A datetime fields saves a date time. How you see that date time is a result of the tool you're using to inspect the data, whether it is Management Studio, or your own software that's printing something from the database.
I strongly recommend keeping it as a datetime field. This will allow you to do date-related operations, such as subtractions and comparisons. If you want to change how your users see the date, then format your date at the presentation layer.
What's happening in the code you've posted is that you're setting the value of A to the same date that it already is. The fact that you're setting that value by means of a string in another format has no relation, SQL server will always have to parse your string input into a date that it can understand. This is why you're not getting an error message. The operation is working, only it's not changing anything.
You can select the date column in specified format or make a view which selects the column value in yyyymmdd format:
SELECT CONVERT(VARCHAR(8), A, 112) FROM Change_Date
It's because the datatype of the column is DATE or DATETIME and it has specific format. If you want to update the column with specific format, make another column and make its datatype VARCHAR. I believe 112 is yyyymmdd format.
I strongly suggest that you keep it AS IS. Database is the storage of data and not for viewing purposes. It is easy to perform task for dates if your data type is DATETIME or DATE. If for instance you want to retrieve the dates with specific format, that's the time you convert your date.
Hope this makes sense.