I have a column ENTRY_MONTH with dates in it as a string like 11/2017.
I'm trying to convert the column to datetime, preferably the last day of each month, so in the example above would be 11-30-2017.
I've tried
CONVERT(datetime, ENTRY_MONTH, 110)
to no avail. Any advice?
select convert(datetime,right(entrymonth,4) + left(entrymonth,2) + '01')
There are so many ways to do this.
Declare #strDate varchar(10) = '11/2017'
-- concatenate '01/' to get the first date of the month.
-- (it is needed to make a proper date,
-- and not necessary to make it the first date, it can be '17/' as well
Select '01/' + #strDate
Select Convert(DateTime,'01/' + #strDate, 103)
-- the EOMONTH can be used here
Select EOMONTH(Convert(DateTime,'01/' + #strDate, 103))
in your case:
EOMONTH(Convert(DateTime,'01/' + ENTRY_MONTH, 103)
You can try something like:
DECLARE #MyDate varchar(16) = '11/2017'
SELECT DATEADD(d,-1,DATEADD(m,1,CONVERT(datetime, '1/' + #MyDate, 103)))
This uses a European format where the day comes first. Add a month on then take a day off takes you to the end of the month.
If you go step by step converting and formatting, you can do it like this (intermediate results shown in the result, too):
DECLARE #entryMonth VARCHAR(7) = '11/2017';
SELECT
#entryMonth AS "entry month",
FORMAT( -- create a date from the parts you have in the varchar and a 1 for the day
DATEFROMPARTS(RIGHT(#entryMonth, 4), LEFT(#entryMonth, 2), 1),
'MM-dd-yyyy' -- and format it the way you want
) AS "First of month",
FORMAT(
DATEADD(MONTH,
1, -- add a month in order to get the first of next month
FORMAT(
DATEFROMPARTS(RIGHT(#entryMonth, 4), LEFT(#entryMonth, 2), 1),
'MM-dd-yyyy')
),
'MM-dd-yyyy'
) AS "First day next month",
FORMAT(
DATEADD(DAY,
-1, -- subtract a day from the first of next month
DATEADD(MONTH, 1, FORMAT(
DATEFROMPARTS(RIGHT(#entryMonth, 4), LEFT(#entryMonth, 2), 1),
'MM-dd-yyyy'))
),
'MM-dd-yyyy'
) AS "Last day entry month"
entry month First of month First day next month Last day entry month
11/2017 11-01-2017 12-01-2017 11-30-2017
Related
Receive date as "19-May" and need to convert it as '05/01/2019', "19-June" to '06/01/2019'.
I have tried various date conversion but it didn't work.
You can try this. Storing date in this format is not a good/suggestion you should use the proper data type which are meant and available for.
You should update the values with proper date time value and then change the data type also. It will save your time & you do not need these conversions every time.
Select Try_Cast('19-May 2019' as Datetime)
OR
Select Try_Cast('19-May' + '2019' as Datetime)
To get the first date of month you can try the below query.
SELECT DATEADD(month, DATEDIFF(month, 0, Try_Cast('19-May 2019' as Datetime)), 0) AS StartOfMonth
Edit
To get the first date of month as per the given data in string, you can use the below query.
declare #dateinStr varchar(20) = '19-May'
Select try_cast('01-' + Replace(#dateinStr, LEFT(#dateinStr, 3), '') + LEFT(#dateinStr, 2) as Datetime) as Date
Here is the demo.
I suppose the months will be 3 chars only, if so then
Select s,
try_Cast(concat(right(s, 3), ' 2019') as Datetime)
from
(
values
('19-May'),
('19-Jun')
) t(s);
If the months is really comes like "June" & "August" then
select s,
try_cast(concat(substring(s, charindex('-',s)+1, 3), ' 2019') as date)
from
(
values
('19-May'),
('19-June'),
('15-August')
) t(s);
If you need to format it as mm/dd/yyyy then use 101 style.
You can do :
SELECT DATEADD(DAY, 1, EOMONTH(CONVERT(DATE, Dates + '-2019'), -1))
FROM ( VALUES ('19-May'), ('19-June')
) t(Dates);
How can I subtract one month from mm/yy in SQL?
For an example from 02/23 to 01/23.
Since your date format is not the recommended one. But for your scenario, you can use the following query to get your expected result.
Using DATEFROMPARTS() and string functions you can construct as a date and the DATEADD(MONTH, -1, date) will help to subtract one month.
DECLARE #TestTable TABLE (DateVal VARCHAR(5));
INSERT INTO #TestTable (DateVal) VALUES ('02/23'), ('01/23'), ('03/30');
SELECT DateVal,
RIGHT(CONVERT(VARCHAR(8), DATEADD(MONTH, -1, DATEFROMPARTS(RIGHT(DateVal, 2), LEFT(DateVal, 2), '01')), 3), 5) AS Result
FROM #TestTable
Result:
DateVal Result
----------------------
02/23 01/23
01/23 12/22
03/30 02/30
Demo on db<>fiddle
I think you need to use convert() to get a valid date, then dateadd() to subtract 1 month and finally format() to get the date in the string format:
select
format(dateadd(month, -1, convert(date, concat('01/', datecolumnname), 3)), 'MM/yy')
from tablename
See the demo.
This comes with a warning is super ugly but if you want string previous month then string again, maybe convert to date do the dateadd then back to string, horrid!
with cte_d
as
(select '01/23' as stringdate
union
select '12/17' as stringdate
)
select stringdate
,cast(Month(dateadd(month,-1,cast(right(stringdate,2)
+ left(stringdate,2) + '01' as date))) as nvarchar(2))
+'/'+
right(cast(Year(dateadd(month,-1,cast(right(stringdate,2)
+ left(stringdate,2) + '01' as date))) as nvarchar(4)),2) as [NewDate]
from cte_d
I need to get date between two date range. That is nth day of nth month.
For example, I need to know 23rd day of every 2nd month between January 1, 2015 to December 30, 2015.
I need the query in T-SQL for SQL Server
You should use recursive query in MSSQL.
Here the first WITH DT is a table where you set up conditions:
WITH DT AS
(
SELECT CAST('January 1, 2015' as datetime) as dStart,
CAST('December 30, 2015' as datetime) as dFinish,
31 as nDay,
2 as nMonth
),
T AS
(
SELECT DATEADD(DAY,nDay-1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DStart), 0)
) as d,0 as MonthNumber
FROM DT
UNION ALL
SELECT DATEADD(DAY,nDay-1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DStart)
+T.MonthNumber+nMonth,0)
)as d, T.MonthNumber+nMonth as MonthNumber
FROM T,DT
WHERE DATEADD(DAY,nDay-1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, DStart)
+T.MonthNumber+nMonth,0)
)<=DT.dFinish
)
SELECT d FROM T,DT WHERE DAY(d)=DT.nDay
SQLFiddle demo
Is this what you are trying to achieve?
DECLARE #startDate datetime
DECLARE #endDate datetime
DECLARE #monthToFind INT
DECLARE #dayToFind INT
SET #startDate = '01/01/2015'
SET #endDate = '12/31/2015'
SET #monthToFind = 2
SET #dayToFind = 20
IF MONTH(#startDate) + (#monthToFind - 1) BETWEEN MONTH(#startDate) AND MONTH(#endDate)
AND YEAR(#startDate) = YEAR(#endDate)
BEGIN
DECLARE #setTheDate datetime
SET #setTheDate = CAST(MONTH(#startDate) + (#monthToFind - 1) AS varchar) + '/' + CAST(#dayToFind AS varchar) + '/' + CAST(YEAR(#startDate) AS varchar)
SELECT DATENAME(DW,#setTheDate)
END
This is clearly homework, and the point of homework is to learn how things work and to solve problems, not to get others to do it for you. So - pointers for doing this properly, rather than an answer to copy and paste.
Numbers / tally tables are ideal for this sort of thing. Create a function that returns a list of sequential integers in a range. More general than a calendar table, and you can use it to derive a calendar table later if you need one.
When you've got that, DATEDIFF will give you the number of days between two dates. Use that to work out the size of your range, DATEADD to increment your date and possibly DATEPART to check that a date is the nth day of the month.
Mess about with those bits for a little while and you'll work it out.
How can I construct a SQL statement that will always return a start date of July 1 of the previous year, and an end date of June 30 of the current year based on GETDATE()? Right now I have
Dateadd(yy, Datediff(yy,1,GETDATE())-1,0) AS StartDate,
DateAdd(dd,-1,Dateadd(yy, Datediff(yy,0,GETDATE()),0)) AS EndDate
which will return January 1, 2012 and December 31, 2013 respectively..
You could just add another DATEADD() to your current script:
SELECT DATEADD(month,6,DATEADD(yy, DATEDIFF(yy,1,GETDATE())-1,0)) AS StartDate
,DATEADD(month,6,DATEADD(dd,-1,DATEADD(yy, DATEDIFF(yy,0,GETDATE()),0))) AS EndDate
This seems like an odd request. One way of doing it is by constructing date strings and parsing them:
select cast(cast(year(GETDATE()) - 1 as varchar(255))+'-07-01' as DATE) as StartDate,
cast(cast(year(GETDATE()) as varchar(255))+'-06-30' as DATE) as EndDate
This constructs the strings in the format '2013-06-30', which will be interpreted correctly on for most SQL Server date settings.
I believe (recalling something Aaron Bertrand wrote) that leaving out the hyphens always works:
select cast(cast(year(GETDATE()) - 1 as varchar(255))+'0701' as DATE) as StartDate,
cast(cast(year(GETDATE()) as varchar(255))+'0630' as DATE) as EndDate
I, as a human, just much prefer having the hyphens.
I've been using this CTE for dynamic fiscal year ranges based on the current date. It returns the start and end dates for the current fiscal year based on the current date.
WITH FYDates AS (
SELECT
CASE
WHEN MONTH(GETDATE()) IN (1, 2, 3, 4, 5, 6)
THEN CAST(CAST(YEAR(GETDATE()) - 1 AS VARCHAR) + '/07/01' AS DATE)
ELSE CAST(CAST(YEAR(GETDATE()) AS VARCHAR) + '/07/01' AS DATE) END AS FYStartDate,
CASE
WHEN MONTH(GETDATE()) IN (1, 2, 3, 4, 5, 6)
THEN CAST(CAST(YEAR(GETDATE()) AS VARCHAR) + '/06/30' AS DATE)
ELSE CAST(CAST(YEAR(GETDATE()) + 1 AS VARCHAR) + '/06/30' AS DATE) END AS FYEndDate
),
You can also create this as a view to reference that when needed.
This should work for you:
SELECT CAST('7/1/' + CAST(DATEPART(yy, Dateadd(yy, Datediff(yy,1,GETDATE())-1,0)) as varchar) as varchar) as startdate,
CAST('6/30/' + CAST(DATEPART(yy, Dateadd(yy, Datediff(yy,0,GETDATE()),0)) as varchar) as varchar) as enddate
I would like select data between two date, without day
An input example:
start month: 9 , start year: 2011
end month: 3, end year: 2012
I think that there are two way to do this.
The first is convert start month and start year to date like 2011-09-01 and convert last date to 2012-03-31, but this requires calculation of the last day of end month. Obtained these date we can use a BEETWEN function for the WHERE clause (but, is the CONVERT function reliable?)
The second solution is to use the DATEPART function like in the following code:
I try to explain: if end year is equal to the initial year, then month must be between the start and end months; else if the final months is greater than the initial years if different from the initial and final year, I take everything in between; else if the final year, the month must be less than or equal to the final month, if the initial year, month must be greater than or equal to the final month
Can you help me do this in the best way? Is correct, the solution I adopted?
declare #IndDebitoCredito bit,#ProgTributo int,#mi as integer,#ai as integer,#mf as integer,#af as integer,#IDAnagrafica varchar(5)
select #mi = 01,#ai = 2011,#mf = 12,#af = 2011,#IDAnagrafica = 'DELEL',#IndDebitoCredito = 1
select distinct rrd.IDTributo
from TBWH_Delega d
--inner join TBWH_SezioneDelega sd on d.IDDelega = sd.IDDelega
inner join TBWH_Rigo rd on rd.IDDelega = d.IDDelega
inner join TBWH_RataRigo rrd on rrd.IDRigo = rd.IDRigo
where
(
DATEPART(MM,d.DataDelega)<=#mf and
DATEPART(MM,d.DataDelega)>=#mi and
DATEPART(YYYY,d.DataDelega)=#ai and
#af = #ai
)
OR
(
--anno finale magg. anno iniziale
#af > #ai AND
(
( -- delega nell'intervallo
DATEPART(YYYY,d.DataDelega)<#af AND
DATEPART(YYYY,d.DataDelega)>#ai
-- DATEPART(MM,d.DataDelega)>=#mi
)
OR
( -- delega limite destro
DATEPART(YYYY,d.DataDelega)=#af AND
DATEPART(MM,d.DataDelega)<=#mf
)
OR
( -- delega limite sinistro
DATEPART(YYYY,d.DataDelega)=#ai AND
DATEPART(MM,d.DataDelega)>=#mi
)
)
)
GO
Your first solution is almost there, but is more complicated than it needs to be and won't work anyway. It will miss out any rows from the last day of the end month.
You can add one month to the end month and then use BETWEEN on the first of each month. eg.
start month: 9 , start year: 2011
end month: 3, end year: 2012
BETWEEN '2011-09-01' AND '2012-04-01'
or, as JNK points out, this will be better:
DataDelega >= '2011-09-01' AND DataDelega < '2012-04-01'
You'll need to add in some logic to deal with the end month being December, but this looks like the simplest way of doing it.
You are WAY overcomplicating this. You really only need two comparisons:
Is the month and year after or equal to the initial value?
Is the month and year before or equal to the final value?
Try:
SELECT *
FROM MyTable
WHERE Datefield BETWEEN
CAST(#mi as varchar) + '/1/' + CAST(#ai as varchar)
-- first of first month
AND
DATEADD(DAY, -1, (DATEADD(Month, + 1, (CAST(#mf as varchar) + '/1/' + CAST(#af as varchar)))))
-- Last day or final month
SELECT *
FROM Table
WHERE DateField
BETWEEN CONVERT(DATE, CONVERT(CHAR(4), #ai) + RIGHT('00' + CONVERT(VARCHAR(2), #mi), 2) + '01', 112)
AND DATEADD(DD, -1, DATEADD(MM, 1, CONVERT(DATE, CONVERT(CHAR(4), #af) + RIGHT('00' + CONVERT(VARCHAR(2), #mf), 2) + '01', 112)))
Avoid using expressions on the DateField columns, as it makes query not SARGable.
I would use:
WHERE DateToCheck >= --- first day of StartMonth
DATEADD( mm, #StartMonth-1,
DATEADD( yy, #StartYear-2000, '2000-01-01')
)
AND DateToCheck < --- first day of next month (after EndMonth)
DATEADD( mm, #EndMonth,
DATEADD( yy, #EndYear-2000, '2000-01-01')
)
DECLARE #mi INT
, #ai INT
, #mf INT
, #af INT
SELECT #mi = 01
, #ai = 2011
, #mf = 12
, #af = 2011
--local variables to hold dates
DECLARE #i DATETIME
, #f DATETIME
--build strings to represent dates in YYYYMMDD format
--add a month to the #f date
SELECT #i = CONVERT(VARCHAR(4), #ai) + RIGHT('0' + CONVERT(VARCHAR(2), #mi),
2) + '01'
, #f = DATEADD(month, 1,
CONVERT(VARCHAR(4), #af) + RIGHT('0'
+ CONVERT(VARCHAR(2), #mf),
2) + '01')
--select data where date >= #i, and < #f
SELECT *
FROM MyTable
WHERE DateField >= #i
AND DateField < #f