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)
Related
Recently I am facing a problem while working with date formats. In the table below I have following dates which is obtained while querying in microsoft SQL Server management studio 2014
select [Month Ending Date] from drug_practise
dates
12/1/2016
11/1/2016
10/1/2016
9/1/2016
8/1/2016
But I need to convert these dates into a proper format such as YYYY-mm-dd, so I used the following code:-
select convert(date,[Month Ending Date],103) from drug_practise
but it throws error as follows :-
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
Anyone can help me how to deal with the dates and avoid such errors ?
I guess you should try format 104 instead of 103 if the first 2 digits represent the day - at least this worked well with the examples provided:
DECLARE #t TABLE(myDateStr CHAR(10))
INSERT INTO #t VALUES
('12/1/2016')
,('11/1/2016')
,('10/1/2016')
,('9/1/2016')
,('8/1/2016')
SELECT myDateStr, TRY_CONVERT(DATE, myDateStr, 104) AS myDate, TRY_CONVERT(VARCHAR(10), TRY_CONVERT(DATE, myDateStr, 104), 23) AS myDateStrNew
FROM #t
If the first two digits represent the month, you can try using format 0 instead:
DECLARE #t TABLE(myDateStr CHAR(10))
INSERT INTO #t VALUES
('12/1/2016')
,('11/1/2016')
,('10/1/2016')
,('9/1/2016')
,('8/1/2016')
SELECT myDateStr, TRY_CONVERT(DATE, myDateStr, 0) AS myDate, TRY_CONVERT(VARCHAR(10), TRY_CONVERT(DATE, myDateStr, 0), 23) AS myDateStrNew
FROM #t
I'm stuck in finding an answer on how to convert:
07-DEC-18 01.00.54.984000 PM to 2018-12-07 13.00.54.984000
I think the time of 01.00.54 PM is 13hours , 0 minutes and 54 seconds
I have try to convert with 112 but still i can't find out how to cast or convert this.
Below is one method that converts the date and time portions separately, and then uses DATEADD to combine the results. This assumes the actual time precision is not greater than milliseconds. Note that you need to use datetime2 instead of datetime to avoid rounding to 1/300 milliseconds.
DECLARE #DateTimeString varchar(30) = '07-DEC-18 01.00.54.984000 PM';
SELECT DATEADD(
millisecond
, DATEDIFF(millisecond, '', CAST(REPLACE(SUBSTRING(#DateTimeString, 11, 8), '.', ':') + RIGHT(#DateTimeString, 10) AS time))
, CAST(LEFT(#DateTimeString, 9) AS datetime2)
);
This converts your value to the datatype it should be, a datetime2(6). Date and time datatypes don't have formats, if you're storing them in a particular format you're doing it wrong (as it means you're storing the value as a varchar).
DECLARE #YourDate varchar(30) = '07-DEC-18 01.00.54.984000 PM';
SELECT V.YD,
TRY_CONVERT(datetime2(6),F.FormatedYD,106)
FROM (VALUES(#YourDate)) V(YD)
CROSS APPLY (VALUES(STUFF(STUFF(V.YD,13,1,':'),16,1,':'))) F(FormatedYD);
If this was a table, then I would fix your actual column datatype by doing the following:
UPDATE YT
SET YourDateColumn = CONVERT(varchar(30),TRY_CONVERT(datetime2(6),F.FormatedYD,106),126)
FROM YourTable YT
CROSS APPLY (VALUES(STUFF(STUFF(YT.YourDateColumn,13,1,':'),16,1,':'))) F(FormatedYD);
ALTER TABLE YourTable ALTER COLUMN YourDateColumn datetime2(6);
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
I am trying to get data after year 2012.
Date is saved in nvarchar format in a table. For example: 12/31/2010
Column also has some other values like 'Confidential', I don't want this row.
I am trying a query (shown below) but it is not succeed :-
select *
from tbl_ProductionWells
where CONVERT(NVARCHAR(10), wellstatusdate, 103) > CONVERT(NVARCHAR(10), '01/01/2012', 103)
Edited :-
I tried this :-
SELECT *
FROM tbl_ProductionWells
WHERE DATEPART(YEAR, CAST(wellstatusdate AS date)) > 2012
But it is giving an error (shown below), This column also has some text values like 'not available','Confidential' .. :-
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Note:- I can't change column datatype as it also contains some other texts.
Thanks in advance
First of all: Store date values in DATE columns, datetimes in DATETIME2 columns. Always choose proper data type for your data
You have to convert your NVARCHAR to DATE, then compare it to 2012-01-01
OR you can extract the 'year' part of your string.
SELECT *
FROM tbl_ProductionWells
WHERE CONVERT(DATE, wellstatusdate) >= '2012-01-01'
The best choice is to change your column's data type to DATE. After that, you can do lots of magicial things with those values. Store the 'Confidental' flag in another column.
EDIT
Some additional info:
Please note, that the STRING -> DATE conversion depends on the current session's language.
Run this batch to see the difference:
DECLARE #DateAsChar VARCHAR(32) = '01/02/12';
SET LANGUAGE us_english
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Hungarian
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Deutsch
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
How about:
WITH cte
AS ( SELECT *
FROM tbl_ProductionWells
WHERE ISDATE(wellstatusdate) = 1
)
SELECT *
FROM cte
WHERE DATEPART(YEAR, CAST(wellstatusdate AS DATE)) > 2012
Select all data from the table that is a date using IsDate, then work with that dataset only.
SELECT * FROM
(SELECT * FROM tbl_ProductionWells WHERE ISDATE(wellstatusdate) = 1)
WHERE CAST(wellstatusdate as Date) > #YOURDATE
Does anyone know how can I format a select statement datetime value to only display time in SQL Server?
example:
Table cuatomer
id name datetime
1 Alvin 2010-10-15 15:12:54:00
2 Ken 2010-10-08 09:23:56:00
When I select the table I like the result will display as below
id name time
1 Alvin 3:12PM
2 Ken 9:23AM
Any way that I can do it in mssql?
You can use a combination of CONVERT, RIGHT and TRIM to get the desired result:
SELECT ltrim(right(convert(varchar(25), getdate(), 100), 7))
The 100 you see in the function specifies the date format mon dd yyyy hh:miAM (or PM), and from there we just grab the right characters.
You can see more about converting datetimes here.
You can use the CONVERT function like this:
SELECT CONVERT(varchar, your_datetime, 108)
However, this is 24-hour clock, no AM/PM.
This will get the time from a datetime value and also give the am or pm add on
SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7)
will always return the date in HH:mmAM format.
Note the lack of space
Or
SELECT REPLACE(REPLACE(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),7)),7),'AM',' AM'),'PM',' PM')
will always return the date in HH:mm AM format.
Hope that helps.
PK
Try:
select convert(varchar, getdate(), 108)
+ ' ' + RIGHT(convert(varchar, getdate(), 100), 2) as Time
You might be able to use:
select
convert(varchar,getdate(),114)
You might be able to manually construct the query like:
string query = string.Format("INSERT INTO test (DateOnlyField, TimeOnlyField) VALUES ('{0}', '1899-12-30 {1}')", DateTime.Today.ToShortDateString(), TimeString)
I dunno if this might work to:
Create Table Schedule( ScheduleID Integer Identity, ScheduledTime DateTime )
Go
Insert Into Schedule( ScheduledTime ) Values( '10:15:00 AM' )
Go
Select ScheduledTime As DBScheduledTime, Convert( VarChar( 10 ), ScheduledTime, 114 ) As ScheduledTime
From Schedule
Go
Drop Table Schedule
Go
If You are using SQL Server 2008 or Higher You can use the following statement:
SELECT Convert( VarChar( 10 ), CAST([columnName] AS TIME(0)), 100 )
If you are using MySql
you can use TIME_FORMAT()
Code ↓↓
SELECT name, time_format(datatime,'%H:%i') as tine from cuatomer