Stripping date from string, casting to date and checking if equal to today's date - sql

I have a character field representing a date in the following format:
'yyyyMMdd-000000'
I'm not completely sure what the 0's represent, but I'm trying to strip those off then check if the date is the same as today's date:
SELECT
acctnum,
acctname
FROM
[Server].[dbo].[Table1]
Where
CAST(LEFT(myDate,8) AS DATE) = CAST(GetDate() as Date)
When executing that statement I get this error:
Conversion failed when converting date and/or time from character string.
What am I doing wrong and how could I fix this?

Use try_cast() instead:
Where TRY_CAST(LEFT(myDate, 8) AS DATE) = CAST(GetDate() as Date)
Then, you can find the bad data using:
select myDate
from [Server].[dbo].[Table1]
Where TRY_CAST(LEFT(myDate, 8) AS DATE) is null;
You can attempt to find the bad data with something like:
select myDate
from [Server].[dbo].[Table1]
where mydate not like '[12][90][0-9][01][0-9][0-9][1-3][0-9]%'
This doesn't find all bad examples, but if something is glaring it will pop.

declare #table1 table
(
acctnum int,
acctname varchar(10),
myDate varchar(20)
)
insert into #table1(acctnum, acctname, myDate)
values(1, 'A', '20200401-000000'),
(2, 'B', convert(varchar(20), getdate(), 112) + '-000000'),
(3, 'C', convert(varchar(20), getdate(), 112) + '-000000'),
(4, 'D', 'abcd-0000');
select *
from #table1;
select *, case isdate(stuffdate) when 1 then cast(stuffdate as date) end
from
(
select *, stuff(stuff(stuff(myDate, 14, 0, ':'), 12, 0, ':'), 9, 1, ' ') as stuffdate
from #table1
where myDate like convert(varchar(20), getdate(), 112)+'%'
) as t;
select *
from
(
select *, stuff(stuff(stuff(myDate, 14, 0, ':'), 12, 0, ':'), 9, 1, ' ') as stuffdate
from #table1
) as t
where case isdate(stuffdate) when 1 then cast(stuffdate as date) end = convert(varchar(20), getdate(), 112);

Related

Get Last date of month SQL

I need to find the last day of a month in the american (mm-dd-yyyy) format for a column which has yymm(nvarchar format).
example:- for 1601---> 01-31-2016
Thank you for help!
Using convert to get the date of the 1st of the month, then dateadd to get the next month, and one more dateadd to get one day before:
DECLARE #D char(4) = '1601'
SELECT DATEADD(DAY, -1, DATEADD(MONTH, 1, CONVERT(date, #D + '01', 12)))
Result:
2016-01-31
With a string of 1601, we just need to append a 01 because the century will be assumed. This new string of 160101 can be converted into a date.
Example
select convert(varchar(10),dateadd(day,-1,dateadd(month,1,YourCol+'01')),101)
From YourTable
Returns
01/31/2016
Since you said year 20XX...
declare #oddDate nvarchar(4) = '1601'
select
DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, '20' + cast(YY as varchar(2)) + cast(MM as varchar(2)) + '01') + 1, 0)) as LastDayof20Year
,'20' + cast(YY as varchar(2)) + cast(MM as varchar(2)) + '01' as MadeUpDate
from
(select
left(#oddDate,2) as YY
,right(#oddDate,2) as MM) x
Or simply...
select
DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, '20' + cast(left(#oddDate,2) as varchar(2)) + cast(right(#oddDate,2) as varchar(2)) + '01') + 1, 0)) as LastDayof20Year
Something like the following should do the trick...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
CharDate CHAR(4) NOT NULL
);
INSERT #TestData (CharDate) VALUES
('9801'), ('9902'), ('0012'), ('0202'), ('1005'), ('1503');
--============================================================
SELECT
FormattedEOM = CONVERT(CHAR(10), em.EndOfMonth, 101)
FROM
#TestData td
CROSS APPLY ( VALUES (CASE WHEN CAST(LEFT(td.CharDate, 2) AS INT) > 30 THEN '19' ELSE '20' END) ) c (Century)
CROSS APPLY ( VALUES (DATEFROMPARTS(CONCAT(c.Century, LEFT(td.CharDate, 2)), RIGHT(td.CharDate, 2), 1)) ) fm (FirstOfMonth)
CROSS APPLY ( VALUES (EOMONTH(fm.FirstOfMonth)) ) em (EndOfMonth);
HTH,
Jason
Edit: The following should work with 2008....
SELECT
FormattedEOM = CONVERT(CHAR(10), em.EndOfMonth, 101)
FROM
#TestData td
CROSS APPLY ( VALUES (CASE WHEN CAST(LEFT(td.CharDate, 2) AS INT) > 30 THEN '19' ELSE '20' END) ) c (Century)
CROSS APPLY ( VALUES (CAST(c.Century + td.CharDate + '01' AS DATE)) ) fm (FirstOfMonth)
CROSS APPLY ( VALUES (DATEADD(mm, 1, fm.FirstOfMonth)) ) nm (NextMonth)
CROSS APPLY ( VALUES (DATEADD(dd, -1, nm.NextMonth)) ) em (EndOfMonth);

How to convert String to Datetime including time part in SQL [duplicate]

This question already has answers here:
How to convert datetime string without delimiters in SQL Server as datetime?
(6 answers)
Closed 6 years ago.
I want to convert below string to DateTime in SQL.
20140601152943767
I know convert(date,'20140601152943767') this but I want time part also.
Above function only returns me Date part.
Thanks in advance.
I would use following solution:
SELECT CONVERT(DATETIME, STUFF(STUFF(STUFF(STUFF('20140601152943767', 9, 0, ' '), 12, 0, ':') , 15, 0, ':'), 18, 0, '.'))
Note #0: All those STUFF calls will convert source strings from 20140601152943767 to 20140601 15:29:43.767.
Note #1: SELECT STUFF('abcef', 4, 1, 'DDD') will replace substring starting from index 4 with a length of 1 char (e) with DDD -> abcDDDf
Note #2: SELECT STUFF('abcef', 4, 0, 'DDD') returns abcDDDef
You can try lik ethis:
select
concat(convert(date,LEFT('20140601152943767',8)), ' ' , Convert(time,Dateadd(SECOND,
Right('20140601152943767',2)/1,
Dateadd(MINUTE,
Right('20140601152943767',4)/100,
Dateadd(hour,
Right('20140601152943767',6)/10000,
'1900-01-01')))) )
as myDate
Output:
2014-06-01 22:38:07.0000000
Well, first of all - you need conversion not to date but to datetime type.
Second - you should always specify format as mentioned:
https://msdn.microsoft.com/en-us/library/ms187928(v=sql.120).aspx
e.g.
select convert(datetime, '20140501', 112)
3 - there is no such format supported for your value demonstrated, so you have to modify your value yo something like yyyy-mm-ddThh:mi:ss.mmm (iso) or to make custom conversion with substring and so on.
;WITH myvalues AS (
SELECT '20140601152943767' value
)
SELECT
convert(date, LEFT(mv.value, 8), 112),
cast(STUFF(STUFF(STUFF(STUFF(mv.[value], 1, 8, ''), 7, 0, '.'), 5, 0, ':'), 3, 0, ':') AS TIME)
FROM myvalues mv
Try This one
declare #datetime varchar(20) = '20140601152943767'
select convert(varchar(20),convert(date,LEFT(#datetime,8))) + ' ' + substring(RIGHT(#datetime,9), 1, 2)
+ ':' + substring(RIGHT(#datetime,9), 3, 2)
+ ':' + substring(RIGHT(#datetime,9), 5, 2)
+ '.' + substring(RIGHT(#datetime,9), 7, 3)
I know some might argue that this is not the best way , but still it's an alternative.Few people have already used convert and stuff functions .
Try this out.Easy to understand.Also test your subqueries.
select y1||'-'||M1||'-'||d1||' '||h1||':'||mi||':'||s1||':'||f1 as xdate
from
(
select substr('20140601152943767',1,4) Y1 from dual
),
(
select substr('20140601152943767',5,2)M1 from dual
),
(
select substr('20140601152943767',7,2) d1 from dual
),
(
select substr('20140601152943767',9,2) h1 from dual
),
(
select substr('20140601152943767',11,2) mi from dual
),
(
select substr('20140601152943767',13,2) s1 from dual
),
(
select substr('20140601152943767',15,3) f1 from dual
)
Output:
2014-06-01 15:29:43.767

Select * from table where date selected is between

i trying to build the following query to select * from table where the minDate is 03-02-2014 and the maxDate is 01-03-2014
but something i missing.
hope that someone can help me with this.
SELECT * From table Where
SUBSTRING(mydate, 1, 10) >= REPLACE('03-02-2014','-','/') AND
SUBSTRING(mydate, 1, 10) <= REPLACE('01-03-2014','-','/')
Note:
My Date column is of type varchar with a value like this --> 03/02/2014 18:13:16
im working in sql server management studio (t-sql)
From your comments, it seems that the mydate column of your table is in the British format.
Read this article about date conversion in SQL SERVER to understand more about date conversions.
Also updated my answer with the date conversions for this format.
Try something like
SELECT * FROM table
WHERE CONVERT(DATE, SUBSTRING(mydate, 1, 10), 103) >= CONVERT(DATE, '03/02/2014', 103)
AND CONVERT(DATE, SUBSTRING(mydate, 1, 10), 103) <= CONVERT(DATE, '01/03/2014', 103)
you can do something like:
Select * From Table
Where CONVERT( Datetime, mydate ,110 ) between CONVERT( Datetime, #min ,110 ) and between CONVERT( Datetime, #max ,110 )
I don't have SSMS available right now, but for a quick try you might try this
SELECT * From table Where
CAST( SUBSTRING(mydate, 1, 10) as date) BETWEEN CAST( SUBSTRING('START DATE', 1, 10) as date)
AND CAST( SUBSTRING('END DATE', 1, 10) as date)

combine 2 varchar column's data and convert to datetime

I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.

SQL Server: Date conversion problem?

I have a column which has date-values stored in varchar (format ddmmyy) like this
231280
121280
131185
...
How to convert these values into datetime data type?
Set DateFormat DMY
GO
Select Cast(Stuff(Stuff(SomeValue, 3, 0, '-'), 6, 0, '-') As datetime)
From MyData
Use substring to get year, month, and day, if year greater than 11 add 19 to it if not add 20, to get year in format 2009, but this is your query just instead of string add your column name
select CAST(
CASE WHEN CAST(SUBSTRING('231280', 5, 2) AS INT) >11
THEN '19'+SUBSTRING('231280', 5, 2)
else '20'+SUBSTRING('231280', 5, 2)
END
+'-'+SUBSTRING('231280', 3, 2)+'-'+SUBSTRING('231280', 1, 2) as datetime)
You'd have to use some substring footwork to convert your string to a known date format. Here's an example converting the string to format 3, "British/French":
declare #YourTable table (YourColumn varchar(50))
insert #YourTable
select '231280'
union all select '121280'
union all select '131185'
select convert(datetime, substring(YourColumn,1,2) + '/' +
substring(YourColumn,3,2) + '/' + substring(YourColumn,5,2), 3)
from #YourTable
Because this format is non standard, use
DECLARE #field char(6)
SET #field = '231280'
select convert(datetime, right(#field, 2) + substring(#field, 3, 2) + left(#field, 2) , 12)