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
Related
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)
I have created a procedure for the purpose of fetching the yesterday data from an Oracle database table and insert it into a SQL Server 2012 table.
Using the following
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT
LEAD(CONVERT(VARCHAR, CONVERT(DATETIME, '01-JAN-1970 03:00:00', 120) + [DAT_CLOSEDATE] / (24 * 60 * 60), 120), 1, CONVERT(VARCHAR, CONVERT(DATETIME, '01-JAN-1970 03:00:00', 120) + [DAT_CLOSEDATE] / (24 * 60 * 60), 120)) OVER (PARTITION BY [TXT_TICKETNUMBER] ORDER BY [DAT_CLOSEDATE]) AS [CLOSE_DATE]
INTO #Temp
FROM OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE ,TXT_TICKETNUMBER
FROM SCHEME.TABLE')
WHERE
[DAT_CLOSEDATE] = DATEADD(d, -1, GETDATE())
SELECT * FROM #Temp
Everything is working as expected when I don't use the WHERE condition.
But once I use the WHERE condition, the following error appears
Msg 8115, Level 16, State 2, Line 4
Arithmetic overflow error converting expression to data type datetime.
NOTE:
The DAT_CLOSEDATE column datatype in the Oracle table is float and its datetime in sql server .
I used the LEAD and CONVERT functions in order to convert its values to be a datetime datatype
I have tried to convert it to date datatype as following.
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT
lead(convert(varchar,convert(date,'01-JAN-1970 03:00:00',120) +
[DAT_CLOSEDATE]/(24*60*60), 120),1,convert(varchar,convert(date,'01-JAN-
1970 03:00:00',120) + [DAT_CLOSEDATE]/(24*60*60), 120)) over(partition by
[TXT_TICKETNUMBER] order by [DAT_CLOSEDATE])AS [CLOSE_DATE]
INTO #Temp
FROM OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE ,TXT_TICKETNUMBER
FROM SCHEME.TABLE')
WHERE [DAT_CLOSEDATE] = DATEADD(d,-1,GETDATE())
SELECT * FROM #Temp
But I got this error
Msg 206, Level 16, State 2, Line 4
Operand type clash: date is incompatible with float
sample data for DAT_CLOSEDTE column in the oracle table which is FLOAT
DAT_CLOSEDATE
1531038410
1531038433
1531038438
1531038447
1531038449
1531038450
1531038506
1531038506
One of the resolution am looking for is I expect OPENQUERY syntax to be something like the following:
OPENQUERY(ORACLE_DB, 'SELECT DAT_CLOSEDATE, TXT_TICKETNUMBER
FROM SCHEME.TABLE
WHERE [DAT_CLOSEDATE] = trunc(sysdate)-1')
but it needs to be converted from FLOAT to DATE data type first.
Here's an example snippet that uses an extra sub-query to transform the FLOAT to a DATETIME.
Which makes further calculations easier.
Since it's an example, the insert into a temp table isn't used.
declare #Table table (TXT_TICKETNUMBER VARCHAR(30), DAT_CLOSEDATE FLOAT);
insert into #Table (TXT_TICKETNUMBER, DAT_CLOSEDATE) values
('foo000042', ((CONVERT(float, DATEADD(hour,-24,GETDATE()))*86400.0)-(25567.0*86400))),
('foo000042', ((CONVERT(float, DATEADD(hour,-23,GETDATE()))*86400.0)-(25567.0*86400))),
('bar000042', ((CONVERT(float, DATEADD(hour,-22,GETDATE()))*86400.0)-(25567.0*86400))),
('bar000042', ((CONVERT(float, DATEADD(hour,-21,GETDATE()))*86400.0)-(25567.0*86400)));
SELECT
TICKETNUMBER,
CLOSEDATETIME,
DAT_CLOSEDATE,
LEAD(CloseDatetime) OVER (PARTITION BY TICKETNUMBER ORDER BY CLOSEDATETIME) AS NextCLOSEDATETIME
FROM
(
select
TXT_TICKETNUMBER AS TICKETNUMBER,
DATEADD(hour,3,CONVERT(datetime,25567.0+(DAT_CLOSEDATE/86400.0))) AS CLOSEDATETIME,
DAT_CLOSEDATE
from
(
-- put the openquery here instead
select TXT_TICKETNUMBER, DAT_CLOSEDATE
from #Table
) q1
) q2
WHERE CAST(CLOSEDATETIME AS DATE) = CAST(DATEADD(day,-1,GETDATE()) AS DATE)
But if you would change that Oracle query to transform that "DAT_CLOSEDATE" to a string.
For example in the YYYY-MM-DD HH24:MI:SS format.
Then that would probably makes the conversion to a T-SQL DATETIME a tad easier.
I have a table with a VARCHAR field called ArrivalDate in format yymmdd (such as 170202).
I am writing a query which converts it to yyyymmdd so it should become 20170202.
However my problem is that I need to cater for the case when inappropriate data is entered into the field, and my query needs to exclude that data. I am achieving this exclusion by using the ISDATE function of TSQL. I also need to select the least recent entry (I'm using order by asc for this).
I am using a variety of converts to write this query, below is my implementation with a sample table and data.
Declare #tmp TABLE (theDates VARCHAR(MAX))
INSERT INTO #tmp VALUES('170202')
SELECT TOP 1 t.theDates
WHEN (ISDATE(t.theDates) = 1) THEN CONVERT( VARCHAR(max),CONVERT(datetime t.theDates), 112)
FROM #tmp t
WHERE (ISDATE(t.theDates) = 1)
ORDER BY CAST(t.theDates as DATE)
However I do not like my approach and it occasionally fails conversion and throws an error with values such as 02/02/02 which breaks the query. Can someone please show me a better way of writing this functionality.
Much appreciated!
You can use TRY_CONVERT and CONVERT to get the correct format and convert the value. Then check that the string is exactly 6 character to prevent other formats from being returned.
SELECT
convert(char(10),convert(date, theDates, 12),112)
FROM
(values('02/02/02'),('170202')) x(theDates)
WHERE
try_convert(date, theDates, 12) is not null
and len(theDates) = 6
You can use cast(#date as datetime)
declare #date varchar(max);
set #date='170202';
select
CASE WHEN (ISDATE(cast(#date as datetime)) = 1)
THEN CONVERT(VARCHAR(max), CONVERT(datetime, cast(#date as datetime)), 112) end
from table
set #date='02/02/02';
select
CASE WHEN (ISDATE(cast(#date as datetime)) = 1)
THEN CONVERT(VARCHAR(max), CONVERT(datetime, cast(#date as datetime)), 112) end
from table
please use create function for check dateformat is Valid or not and use this fun in your query inside cash clouse.
ALTER FUNCTION dbo.f_CheckDate
(#InDate nvarchar(25))
RETURNS DATE
AS
BEGIN
declare #Return DATETIME
select #return = CASE WHEN ISDATE(#InDate) = 1
THEN #InDate
ELSE NULL
END
return #return
END
You could use TRY_CAST or TRY_CONVERT if value cannot be cast it will return NULL.
SELECT
TRY_CAST('20170228' AS DATETIME),
TRY_CAST('170228' AS DATETIME),
TRY_CONVERT(DATETIME, '20170228'),
TRY_CONVERT(DATETIME, '170228')
This works for SQL Server 2012 and newer.
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