TSQL Month and Year to Date Conversion - sql-server

I have a table that stores an int for month and year. I need to convert that to a date (we can use the first day of the month and the day).
I tried something like below but got an error about converting int to date
AND CAST(ym.year + '-' + ym.month + '-' + '01' AS DATE) BETWEEN #startDate AND #endDate
End result should be be something like 2016-05-01 so I can check the date against a start and end date that I pass to the function.

You could try something like this, modified for your use:
declare #YY int = 2016
declare #MM int = 5
select CAST(CAST(#YY as varchar(4)) + '-' + RIGHT('00' + CAST(#MM as varchar(2)),2) + '-01' as DATE)

From SQL Server 2012 on you can use DATEFROMPARTS
AND DATEFROMPARTS(ym.year, ym.month, 1) BETWEEN #startDate AND #endDate

AND DateFromParts(ym.year, ym.month, 1) BETWEEN #startDate AND #endDate
EDIT: For old versions of SQL:
SELECT CAST(CAST(ym.year*10000+ym.month*100+1 AS CHAR(8)) AS DATETIME)

Try this :
CAST(CAST(ym.year AS varchar) + '-' + CAST(ym.month AS varchar) + '-01' AS DATETIME)

This will work if you are on 2008 or lower
select cast(
cast(ym.year as varchar(4))+
case when len(ym.month) < 2 then '0' + cast(ym.month as varchar(2)) else cast(ym.month as varchar(2)) end +
'01' as date)
The Error you are getting is because when you CONCAT your INT values there is no leading 0 for days before 10, or months before October, thus your CAST to DATE is essentially missing values to do the conversion. Here we are padding based off the length.

You could go the data way and create a table of year, month and date as first of month then join the tables. this may be faster for a large table especially if the number of years and months in the original table is limited.
So if you have a years data in your original table there would only be 12 records required, which as a join added into your processing should be quick.
To avoid missing dates, build the lookup table from original data:
SELECT year, month, cast(cast(year*10000+month*100+1 as char(8)) as date) as FirstOfMonth
INTO #FirstOfMonth FROM mytable GROUP BY year, month

Related

How to get date from yyyy-mm-dd to yyyy-mm-dd in SQL?

I want to get date from yyyy-mm-dd to yyyy-mm-dd in SQL.
Example: I have two parameter #startdate : 2015-12-28 and #enddate : 2016-01-02, and database in SQLServer, datatype is varchar(10)
DATE_ORDER
28-12-2015
30-12-1996
29-12-2016
30-12-1997
24-12-2015
27-12-1993
03-01-2016
01-01-1992
02-01-2016
etc...
Ok,now I want to get data from #startdate : 2015-12-28 and #enddate : 2016-01-02. I use SELECT * FROM TABLE_X WHERE DATE_ORDER >= #startdate AND DATE_ORDER <= #enddate . But the results are not what I expected. Here are the results I want
28-12-2015
30-12-1996
29-12-2016
30-12-1997
01-01-1992
02-01-2016
I think to solve this problem, I need to do two things :
First, get date range from #startdate to #enddate , in here 28/12/2015, 29/12/2015, 30/12/2015, 31/12/2015, 01/01/2016, 02/01/2016.
The second: get the date in database same in range 28/12, 29/12, 30/12, 31/12, 01/01, 02/01, ignoring the year.
Can you give me some ideas about this ?
Your actual format is "105-italian" find details here.
You can convert your existing VARCHAR(10)-values with this line to real datetime
SELECT CONVERT(DATETIME,YourColumn,105)
Next thing to know is, that you should not use BETWEEN but rather >=StartDate AND < NakedDateOfTheFollowingDay to check date ranges
So to solve your need Get date-range from 2015-12-28 to 2016-01-02 you might do something like this:
DECLARE #Start DATETIME={d'2015-12-28'};
DECLARE #End DATETIME={d'2016-01-02'};
SELECT *
FROM YourTable
WHERE CONVERT(DATETIME,YourDateColumn,105)>=#Start AND CONVERT(DATETIME,YourDateColumn,105)<#End+1
Attention Be aware, that the conversion lets your expression be not sargable. No index will be used.
Better was to store your date as correctly typed data to avoid conversions...
Try this query
SET DATEFIRST 1
DECLARE #wk int SET #wk = 2
DECLARE #yr int SET #yr = 2011
--define start and end limits
DECLARE #todate datetime, #fromdate datetime
SELECT #fromdate = dateadd (week, #wk, dateadd (YEAR, #yr-1900, 0)) - 4 -
datepart(dw, dateadd (week, #wk, dateadd (YEAR, #yr-1900, 0)) - 4) + 1
SELECT #todate = #fromdate + 6
;WITH DateSequence( Date ) AS
(
SELECT #fromdate AS Date
UNION ALL
SELECT dateadd(DAY, 1, Date)
FROM DateSequence
WHERE Date < #todate
)
--select result
SELECT * FROM DateSequence OPTION (MaxRecursion 1000)
So, after the 2nd or 3rd edit, it slowly becomes clear, what you want (i hope).
So you REALLY WANT to get the dates with the year beeing ignored.
As someone pointed out already, date-values are stored internally not as string, but as internal datatype date (whatever that is in memory, i don't know).
If you want to compare DATES, you cannot do that with ignorance of any part. If you want to, you have to build a NEW date value of day and month of given row and a hard coded year (2000 or 1 or whatever) for EVERY row.
SELECT * FROM TABLE_X WHERE convert(date,'2000' + substring(convert(char(8),convert(datetime, 'DATE_ORDER', 105),112),5,4),112) >= #startdate AND convert(date,'2000' + substring(convert(char(8),convert(datetime, 'DATE_ORDER', 105),112),5,4),112) <= #enddate
If your startdate and enddate go OVER sylvester, you have to do 2 queries, on from startdate to 1231, one from 0101 to enddate.

SQL Server: Convert a month name (string) to a date

I have a table with a month name in it as type varchar. e.g. "November". Can I convert this to a date field?
CONVERT(DATETIME,main.ReportMonth) AS ReportMonthDate
CAST(main.ReportMonth AS DATETIME) AS ReportMonthDate
both result in a conversion failure.
I'm using SQL Server 2008.
You can hard code a string value at the end of your input value. Something like this.
declare #ReportMonth varchar(10) = 'November'
select cast(#ReportMonth + ' 1, 2015' as date)
Or if you want to make the year portion be dynamic based on the current date you could modify that slightly like this.
select cast(#ReportMonth + ' 1, ' + cast(datepart(year, getdate()) as char(4)) as date)

SQL Selecting only records matching year and month between two dates

I am making a SQL procedure to get me a selection of workers from the table,
where each worker has startJob and endJob date.
What I need is to make selection of all the workers who were on the job
during specified #year and #month. (#year & #month are input params)
I would really appreciate an advice how to solve this the easiest way.
Thx for any help.
If i proper understood you then try something like:
CREATE PROCEDURE [usp_Procedure]
#Year int
, #Month int
AS
BEGIN
select * from workers
where #Year between YEAR(startJob) and YEAR(endJob)
and #Month between MONTH(startJob) and MONTH(endJob)
END
You can make a date from the year and month parameters and compare to the start and end job fields.
This will return the first day of the month/year entered, and return results where this date is between the StartJob and EndJob
select *
from worker
where
CAST(
CAST(#Year AS VARCHAR(4)) +
RIGHT('0' + CAST(#month AS VARCHAR(2)), 2) +
RIGHT('0' + CAST(01 AS VARCHAR(2)), 2)
AS DATETIME)
between
StartJob and EndJob
Create a DATE based on the start of the month for the given year
DECLARE #Year INT = 1999
DECLARE #Month INT = 1
DECLARE #Date DATE = CONVERT(DATE, CONVERT(CHAR, #Month) + '-' + CONVERT(CHAR, #Month) + '-01')
-- SQL Server should now correctly handle the logic to filter out the relevant rows
SELECT *
FROM worker w
WHERE #Date BETWEEN w.startJob AND w.endJob
If you'd rather use the last day of the month, then you could use EOMONTH(#Month) for your DAY.
FINAL SOLVED SELECT ROWS BETWEEN TWO DATE USING ONLY MONTH AND YEAR
begin
declare #trvl_start_date as date
declare #trvl_stop_date as date
declare #trim_start as varchar(20)
declare #trim_end as varchar(20)
declare #trvl_start_date_new as date
declare #trvl_stop_date_new as date
set #trvl_start_date ='2015-10-12'
set #trvl_stop_date='2016-01-01'
set #trim_start = LEFT(#trvl_start_date, CHARINDEX('-', #trvl_start_date) + 2) + '-01'
set #trim_end = LEFT(#trvl_stop_date, CHARINDEX('-', #trvl_stop_date) + 2) + '-01'
print #trim_start
print #trim_end
set #trvl_start_date_new = #trim_start
set #trvl_stop_date_new =dateadd(month,-1,#trim_end)
print #trvl_start_date_new
print #trvl_stop_date_new
SELECT fee_catg_srno FROM dbo.fee_catg_tbl
WHERE (acd_yr = 1) AND (recycle = 1) AND (acc_head_srno = 3) AND pay_date between #trvl_start_date_new and #trvl_stop_date_new
end

SQL Server - how to dynamically determine financial year?

Every year I have to update my company's financial reports to include the new financial year (as the year isn't coterminus with the calendar year), so I do.....
Case
when ST_date >= '1996.11.01 00:00:00' and st_date < '1997.11.01 00:00:00'
then '96-97'
[etc]
end as year,
Every year I have to remember which reports I need to amend - most years I forget one!
...Is there a simple dynamic way to determine this?
You could definitely write a simple stored function in SQL Server to determine the financial year based on the date:
CREATE FUNCTION dbo.GetFinancialYear (#input DATETIME)
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #FinYear VARCHAR(20)
SET #FinYear =
CASE
WHEN #INPUT >= '19961101' AND #input < '19971101' THEN '96-97'
WHEN #INPUT >= '19971101' AND #input < '19981101' THEN '97-98'
ELSE '(other)'
END
RETURN #FinYear
END
and then just use that in all your queries.
SELECT
somedate, dbo.GetFinancialYear(somedate)
......
If you need to add a new financial year - just update the one function, and you're done !
Update: if you want to make this totally dynamic, and you can rely on the fact that the financial year always starts on Nov 1 - then use this approach instead:
CREATE FUNCTION dbo.GetFinancialYear (#input DATETIME)
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #FinYear VARCHAR(20)
DECLARE #YearOfDate INT
IF (MONTH(#input) >= 11)
SET #YearOfDate = YEAR(#input)
ELSE
SET #YearOfDate = YEAR(#input) - 1
SET #FinYear = RIGHT(CAST(#YearOfDate AS CHAR(4)), 2) + '-' + RIGHT(CAST((#YearOfDate + 1) AS CHAR(4)), 2)
RETURN #FinYear
END
This will return:
05/06 for a date such as 2005-11-25
04/05 for a date such as 2005-07-25
Have a look at this example:
declare #ST_Date datetime = '20120506'
SELECT
convert(char(2),DateAdd(m,-10,#ST_DATE),2)+'-'+
convert(char(2),DateAdd(m,+ 2,#ST_DATE),2) as year
As a column expression:
convert(char(2),DateAdd(m,-10,ST_DATE),2)+'-'+
convert(char(2),DateAdd(m,+ 2,ST_DATE),2) as year
Pretty trivial!
The way I handle these problems (financial year, pay period etc) is to recognize the fact that financial years are the same as any year, except they start X months later. The straightforward solution is therefore to shift the FY by the number of months back to the calendar year, from which to do any "annual" comparisons or derivation of "year" (or "month").
Declare #FinancialMonth Varchar(100)=NULL,#Month smallint,#Date DateTime='04/06/2013'
BEGIN TRY
SELECT #FinancialMonth='01-'+IsNULL(#FinancialMonth,'April')+'-'+Cast(year(getdate()) as varchar)
SELECT #Month=(Month(Cast(#FinancialMonth as datetime))-1) * -1
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,'Invalid Financial Month' ErrorMessage
END CATCH
SELECT Month((CONVERT([varchar](10),dateadd(month,(#Month),#Date),(101)))) FinancialMonth,
Year((CONVERT([varchar](10),dateadd(month,(#Month),#Date),(101)))) FinancialYear
,DatePart(qq,(CONVERT([varchar](10),dateadd(month,(#Month),#Date),(101)))) FinancialQuarter
This one works for me and sets it as the actual FY end date.
SET #enddatefy = convert(DATE, str(datepart(yyyy,DateAdd(m,-6,#enddate))+1)+'0630',112)
SET #enddatefyid = str(datepart(yyyy,DateAdd(m,-6,#enddate))+1)+'0630'
datename(YEAR, DATEADD(M,-3,Date)) +'-'+ cast((datepart(YEAR, DATEADD(M,-3,Date)) + 1) %100 as varchar(2))
Calculate on Column 'Date'
Financial year ranges from 1st April to 31st March
Create FUNCTION dbo.GetFinancialYear (#input DATETIME)
RETURNS VARCHAR(20)
AS BEGIN
DECLARE #FinYear VARCHAR(20)
IF (MONTH(#input) > 3)
SET #FinYear = RIGHT(CAST(Year(#input) AS CHAR(4)), 4) + '-' + RIGHT(CAST((Year(#input) + 1) AS CHAR(4)), 2)
ELSE
SET #FinYear = RIGHT(CAST((Year(#input) - 1) AS CHAR(4)), 4) + '-' + RIGHT(CAST(Year(#input) AS CHAR(4)), 2)
RETURN #FinYear
END
Declare #date1 datetime = '2017-07-01'
Select Case
When Month(#date1)>=7 Then 'FY'+Convert(NVARCHAR(10),(Right(year(getdate()),2)+1))
Else 'FY'+Convert(NVARCHAR(10),(Right(year(getdate()),2)))
End
This works for me, where the financial year starts in July.
CASE WHEN DatePart(mm, [YourDate]) >= 7
THEN convert(varchar(10), YEAR([YourDate])) +' / '+ Convert(varchar(10), YEAR([YourDate]) + 1 )
ELSE Convert(varchar(10), YEAR([YourDate]) - 1) +' / '+ Convert(varchar(10), YEAR([YourDate]) )
END AS [Financial Year],

In TSQL, how would you convert from an int to a datetime and give the age?

What would be the sql for the following,
I have a date of birth in an int field,
ie YYYYMMDD = 19600518
I would like to get the age.
None of the other answers are actually calculating age. They're calculating the number of year boundaries and not taking the birthday into account.
To calculate the age, you'll need to do something like this:
DECLARE #d DATETIME
SET #d = CONVERT(DATETIME, CONVERT(VARCHAR(8), 19600518), 112)
SELECT DATEDIFF(year, #d, GETDATE())
- CASE WHEN DATEADD(year, DATEDIFF(year, #d, GETDATE()), #d) <= GETDATE()
THEN 0 ELSE 1 END AS Age
Most of the other answers are not calculating age - just whole years (e.g. Jan 1 2009 is one "year" after Dec 31 2008). Thus, if you use most of the calculations on this page, you will return an incorrect age for half of the year, on average. Luke is the only person who has seen this but his answer strikes me as too complicated - there is an easier way:
Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age
(NOTE: Thanks go to 'Learning' for making a great catch on my original algorithm - this is a revision that uses hours instead of days)
Because the rounding here is very granular, this is almost perfectly accurate for every day of every year. The exceptions are so convoluted that they are almost humorous: every fourth year the age returned will be one year too young if we A) ask for the age before 6:00 AM, B) on the person's birthday and C) their birthday is after February 28th. Of course, depending on what time someone was born this might 'technically' be correct! In my setting, this is a perfectly acceptable compromise.
Here is a loop that prints out ages to show that this works.
Declare #age int;
Declare #BirthDate datetime;
Declare #Year int;
Set #Year = 2008;
WHILE (#Year > 1930)
BEGIN
-- Put today's date where you see '-03-18'
SET #BirthDate = CAST(Cast(#Year as varchar(4)) + '-03-18' AS DATETIME)
SELECT #age=CAST(DATEDIFF(hh, #BirthDate, GETDATE()) / 8766 AS int);
Print Cast(#Year as varchar) + ' Age: ' + Cast(#age as varchar);
Set #Year = #Year - 1;
END;
Finally, this is the version that will also convert Paul's integer date to a real date:
CAST(DATEDIFF(hh, Convert(Datetime, Convert(varchar(8), [birthdate]), 112), GETDATE()) / 8766 AS int) AS Age
DECLARE #dateSt VARCHAR(8)
DECLARE #startDt DATETIME
-- Set the start date string
SET #dateSt = '19600518'
-- Make it a DATETIME (the ISO way)
SET #startDt = CAST(SUBSTRING(#dateSt, 1, 4) + '-' +
SUBSTRING(#dateSt, 5, 2) + '-' +
SUBSTRING(#dateSt, 7, 2) AS DATETIME)
-- Age in Days
SELECT DATEDIFF(D, #startDt, getdate())
Age in years :
select datediff(YY, convert(datetime, convert(varchar, 19600518)), getdate())
[EDIT]
-- I forgot to declare the variables
declare #birthday datetime;
set #birthday = convert(datetime,convert(varchar, 19600518), 112);
declare #datetoday datetime;
set #datetoday = getdate();
select
(
CASE
WHEN dateadd(year, datediff (year, #birthday, #datetoday), #birthday) <= #datetoday
THEN datediff (year, #birthday, #datetoday)
ELSE datediff (year, #birthday, #datetoday) - 1
END) as age;
Here's a one-liner way to do it:
CONVERT(DATETIME, CONVERT(VARCHAR(8),19600518), 112)
But beware! This relies on T-SQL, and probably won't work in other SQL environments.
Please note that the "style" of 112 is simply the "ISO" date format of yyyymmdd. (Something I found in some CONVERT documentation.)
This is a reason why you should NOT ever store dates as anything except a datetime datatype. The best fix is to change your datatype and convert all the dates once (wouldn't be surprised if there are few invalid ones in there either). then you never have to do these workarounds again.
I worked it out and got same as #Learning
select dob, datediff(year, convert(datetime, convert(varchar(8),[dob])) ,getdate()) as age
from [mytable]
where IsDate(convert(varchar(8),[dob])) = 1
NB. I needed the IsDate as well as there were some invalid dates in the data.
Edit. Here is an article from SQLServerCentral on calculating age.

Resources