How to change date-time format? - sql-server

I have a RegDate column of nvarchar(max) type in my table in which dates are stored in mm/dd/yyyy (5/22/2015 11:09:39 PM) and dd-mm-yyyy (19-05-2015 22:55:05) format. I want to get all these entries in one format i.e. dd/mm/yyyy. I tried to convert it by using
Convert(varchar(10),cast(vr.RegDate as DATETIME),105) as RegistrationDate
but it gives following error:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
Please help me regarding this problem.

You need to determine the format of the value you are converting before you can convert it. If it's simply between those two formats, you can simply search for - to determine it's format.
I would also suggest storing the value in a datetime column as opposed to a varchar, and if you can't do that for whatever reason, you should definitely store it in an ISO format: YYYY-MM-DD HH:MM:SS.
Here's a sample that uses a case statement to provide optional formatting of your two date formats, using the presence of the - character:
CREATE TABLE #temp ( RegDate VARCHAR(50) )
INSERT INTO #temp
( RegDate )
VALUES ( '5/22/2015 11:09:39 PM' ),
( '19-05-2015 22:55:05' )
SELECT CASE WHEN CHARINDEX('-', RegDate) != 0
THEN CONVERT(DATETIME, RegDate, 105)
ELSE CONVERT(DATETIME, RegDate, 101)
END AS FormattedToDate
FROM #temp
DROP TABLE #temp
Produces:
FormattedToDate
2015-05-22 23:09:39.000
2015-05-19 22:55:05.000

Related

Text Date Convert issues

I have a data source with 'datetime' that is plain text and am having issues converting it.
When I attempt to convert it to various date formats and INSERT into a new table, I am getting errors.
data example:
"18-07-2015 11:50:30am"
source table structure:
CREATE TABLE [dbo].[Conv_COMMUNICATIONEXPORT]([datetime] [varchar](255) NULL)
destination table structure:
CREATE TABLE [dbo].[TB_X_Attachment]([CreatedDate] [datetime] NULL)
error inserting data:
Msg 242, Level 16, State 3, Line 4
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
When I run the following select, the last convert returns an error:
SELECT CONVERT(VARCHAR(30), GETDATE(), 120) ,getdate() ,CONVERT(DATE, CONVERT(VARCHAR(40), '01-01-2000'), 120)
When I run the following into the table, there is success:
INSERT INTO TB_X_Attachment (CreatedDate)
CONVERT(DATE, CONVERT(VARCHAR(30), '2000-01-01'), 120) AS WORKS
None of the following conversion attempts works when trying to insert:
SELECT ce.[datetime] AS VARCHAR_DATETIME,
CONVERT(VARCHAR(10), CE.[datetime], 120),
CONVERT(char(10), CONVERT(VARCHAR(10), CE.[datetime], 120),120),
CONVERT(VARCHAR(10),CONVERT(char(10), CONVERT(VARCHAR(10), CE.[datetime], 120),120),120),
CONVERT(VARCHAR,(CONVERT(VARCHAR(10), CE.[datetime], 120))) ,
CONVERT(VARCHAR(10), CE.[datetime], 120)
FROM Conv_ATTACHMENTEXPORT ae
INNER JOIN Conv_COMMUNICATIONEXPORT ce
ON ae.[attachment record id] = ce.[communication id]
See image below of the results of the above convert trys
I think if I can reverse the output to YYYY-MM-DD it may work. All the convert attempts dont want to set the format to this. How can I reverse the output to YYYY-MM-DD?
SQL Server is pretty smart when it comes to converting strings to dateTime values.
However, as smart as it is, string representations of date and time values are pretty tricky - that's why we have the ISO 8601 standard which is guaranteed to always be interpreted correctly by SQL Server when converting to datetime.
However, I understand that you don't have any control over the source data, and therefor must handle the format specified.
A quick look at the Date and Time Styles table in the documentation of the Convert function will give you the following formats:
Without With Standard Input/Output (3)
century (yy) (1) century (yyyy)
3 103 British/French 3 = dd/mm/yy
103 = dd/mm/yyyy
4 104 German 4 = dd.mm.yy
104 = dd.mm.yyyy
5 105 Italian 5 = dd-mm-yy
105 = dd-mm-yyyy
Any one of the three options with century would give you a correct value of DateTime for the specified string:
DECLARE #DateString varchar(30) = '18-07-2015 1:5:3pm';
SELECT #DateString As string,
CONVERT(DateTime2, #DateString, 103) As [103],
CONVERT(DateTime2, #DateString, 104) As [104],
CONVERT(DateTime2, #DateString, 104) As [105]
Result:
string 103 104 105
18-07-2015 1:5:3pm 2015-07-18 13:05:03 2015-07-18 13:05:03 2015-07-18 13:05:03
Since the original string use hyphens as a separator, I would go with the Italian standard (105) because it's the closest to the source string format.
Try this:
select convert(datetime, [datetime], 105)
where [datetime] is your varchar column which has the date to be converted
or simply
select convert(datetime, '18-07-2015 11:50:30pm', 105)

SQL insert not inserting converted date format

I am trying to insert records from one table into another and convert varchar to a date format with type of 101 (mm/dd/yyyy). The wierd thing that happens is that once i run stored procedure the source table data format changes but the destination shows the old format of (yyyy-mm-dd)
Any suggestions. See stored procedure below
INSERT INTO Sales
(
DEALER
,UW
,SKU
,SKU_DESCRIPTION
,EARNING_TYPE
,TERM
,PRODUCTPURCH
,CONTRACTPURCH
,ACCOUNTINGPURCH
,CONTRACTS_SUM
,PREMIUM
,RESERVE
,FEES
)
SELECT TmpSales.[DEALER]
,TmpSales.[UW]
,TmpSales.[SKU]
,TmpSales.[SKU_DESCRIPTION]
,TmpSales.[EARNING_TYPE]
,TmpSales.[TERM]
,convert(date,TmpSales.[PRODUCTPURCH], 101) as PURCHDATE
,convert(date,TmpSales.[CONTRACTPURCH], 101) as CONPURCHDATE
,convert(date,TmpSales.[ACCOUNTINGPURCH], 101) as ACCDATE
,TmpSales.[CONTRACTS_SUM]
,(TmpSales.[RESERVE] + TmpSales.[FEES]) as PREMIUM
,TmpSales.[RESERVE]
,TmpSales.[FEES]
FROM [dbo].[Tmp_Sales_Upld] as TmpSales

SQL Server convert number to date

How do I convert a numbers in the columns with values like 20160912 into date formats of the form 09/12/2016 and order them by the dates in the date format.
You can use cast and convert built-in functions. Depending on what type is 20160912 you can do following.
A) int
declare #d int=20160912
select convert(varchar(20),convert(date,convert(varchar,#d)),101)
--step by step
declare #dStr varchar(20)
set #dStr = convert(varchar,#d) --'20160912'
-- or = cast(#d as varchar)
declare #dDate date --or datetime
set #dDate = convert(date, #dStr) --2016-09-12 (this is external representation)
--show in MM/dd/yyyy format
select convert(varchar(20), #dDate, 101) --magic 101 for MM/dd/yyyy
--09/12/2016
B) varchar just omit innermost conversion

How to convert varchar into datetime and skip not valid datetime in TSQL

I have a database in SQL Server. I do not have authorization to change any table but I can create views.
I have three varchar columns which store dates in the format YYYYMMDD. I want to create a view where the dates are converted from varchar to datetime.
Now it can be the case that instead of a date in this columns I can have empty space, NULL or the character -.
Let's take the closedDate column. If I use CONVERT(datetime, closedDate, 112)
Valid dates are converted correctly,
When there is empty space the date is converted to 1900-01-01,
NULL is kept,
The - causes a conversion error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
How can I tell to the function to convert dates just if it has valid date form and leave NULL or better an empty date(or space) in all the other cases?
Try this
CASE WHEN ISDATE(closedDate) = 1 THEN CONVERT(datetime, closedDate, 112)
ELSE NULL END closedDate
Use below code
SELECT CASE WHEN ISDATE(datecolumn)=1 THEN CONVERT(datetime, datecolumn, 103 )
ELSE null END
FROM tablename
use below for empty data
SELECT CASE WHEN ISDATE(datecolumn)=1 THEN CONVERT(datetime, datecolumn, 103 )
ELSE '' END
FROM tablename

How to convert this varchar values to a datetime

I want to convert a varchar value that iI set up to a date time value. I want to load rows of a database into another database, but conversion is not going well.
This is my query:
select Krant
, cast(jaar as varchar(4))+'-'
+RIGHT('0'+cast(maand as varchar(2)),2)+'-'
+RIGHT('0'+cast(dag as varchar(2)),2) as datum
, Inhoud as artikel
, LEN(Inhoud)-LEN(Replace(Inhoud,' ','')) as numwords
, 'Goirle' as vestiging
from [Sitecore_Bibliotheekmb_Krantenknipsel].[dbo].[KRANGOI]
The cast to Datum has to be a datetime value, but i am not getting it to work properly. When i tried to cast to datetime it gave me an out of range exception.
These are the results of this query:
alt text http://94.100.115.48/837450001-837500000/837478801-837478900/837478868_5_dE_7.jpeg
I want the "Datum" field to be a Datetime field with the same values but in Datetime format. Could anyone help me please :).
Thanks,
Younes
Use this:
select Krant, cast(cast(jaar as varchar(4))+'-'
+RIGHT('0'+cast(maand as varchar(2)),2)+'-'
+RIGHT('0'+cast(dag as varchar(2)),2) as datetime) as datum,
Inhoud as artikel,
LEN(Inhoud)-LEN(Replace(Inhoud,' ','')) as numwords,
'Goirle' as vestiging
from [Sitecore_Bibliotheekmb_Krantenknipsel].[dbo].[KRANGOI]
You are not casting the Varchars to a Datetime
CAST and CONVERT on MSDN.
Can you try this:
SELECT CAST(('2010' + '-' + '01' + '-' + '06') AS DATETIME)
If any of your dates are earlier than 1753, a simple datetime type will not be sufficient. For this, you'd need to use the datetime2 datatype introduced in SQL Server 2008.
Also check that all values of maand and dag are valid days and months.

Resources