how to get data dynamically in view basing on fiscal year - sql

How can i create a view Dynamically to get the data based on fiscal year(Financial year).
Lets have look at sample data where im having sample data.
Declare #t table(StartDate date )
insert into #t values('04/01/2012'),
('01/01/2012'),
('09/15/2013'),
('04/01/2014'),
('01/01/2015'),
('09/15/2015'),
('04/01/2016'),
('01/01/2017'),
('09/15/2016')
Just take an example if I have ran the view today I need to get from March 2016 to April 2017. If I have ran view on May 2017 I need to get data from march 2017 to upto may 2017.
I can work it out in Sql server scripts or Stored procedure but how can I achieve the same result in Dynamic View or View .
Suggest me !
my script
DECLARE #STARTDATE DATETIME, #ENDDATE DATETIME,#CURR_DATE DATETIME
SET #CURR_DATE='2016-06-01'
IF MONTH(#CURR_DATE) IN (1,2,3)
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
END
ELSE
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
END
select * from #t
where StartDate between
#STARTDATE AND #ENDDATE
order by year (StartDate)
it's giving data what I want for the fiscal year (2016-2017)
but how can I use this and create a VIEW

select t.*,getdate()
from #t t
where year(startdate) * 100 + month(startdate) >=
case
when month(getdate()) in (1,2,3) then (year(getdate()) * 100) + 3 - 100
else (year(getdate()) * 100) + 3
end

You can use cte with dates based on current date (GETDATE()) in a view:
;WITH cte AS (
SELECT CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE())-1 AS VARCHAR)+'/04/01' AS DATE) ELSE CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/04/01' AS DATE) END AS StartDate,
CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/03/31' AS DATE) ELSE CAST( CAST(YEAR(GETDATE())+1 AS VARCHAR)+'/03/31' AS DATE) END AS EndDate
)
SELECT t.*
FROM YourTable t
INNER JOIN cte c
ON t.StartDate between c.StartDate AND c.EndDate
ORDER BY year(t.StartDate)

If you already worked out the code in a script\stored procedure you can re-use such code in a Table-Valued User-Defined Functions.
That way you will be able to query the UDF like a view.

You can try something like this:
select t.*
from #t t
cross join (
select startdate = case
when MONTH(#CURR_DATE) IN (1,2,3)
then CAST( CAST(YEAR(#CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
else CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
end) s
cross join (
select enddate = case
when MONTH(#CURR_DATE) IN (1,2,3)
then CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
else CAST( CAST(YEAR(#CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
end) e
where t.StartDate between s.startdate and e.enddate
order by year (t.StartDate)

Related

my end goal is to see end of month data for previous month

My end goal is to see end of month data for previous month.
Our processing is a day behind so if today is 7/28/2021 our Process date is 7/27/2021
So, I want my data to be grouped.
DECLARE
#ProcessDate INT
SET #ProcessDate = (SELECT [PrevMonthEnddatekey] FROM dbo.dimdate WHERE datekey = (SELECT [datekey] FROM sometable [vwProcessDate]))
SELECT
ProcessDate
, LoanOrigRiskGrade
,SUM(LoanOriginalBalance) AS LoanOrigBalance
,Count(LoanID) as CountofLoanID
FROM SomeTable
WHERE
ProcessDate in (20210131, 20210228,20210331, 20210430, 20210531, 20210630)
I do not want to hard code these dates into my WHERE statement. I have attached a sample of my results.
I am GROUPING BY ProcessDate, LoanOrigRiskGrade
Then ORDERING BY ProcessDate, LoanOrigIRskGrade
It looks like you want the last day of the month for months within a specified range. You can parameterize that.
For SQL Server:
DECLARE #ProcessDate INT
SET #ProcessDate = (
SELECT [PrevMonthEnddatekey]
FROM dbo.dimdate
WHERE datekey = (
SELECT [datekey]
FROM sometable [vwProcessDate]
)
)
DECLARE #startDate DATE
DECLARE #endDate DATE
SET #startDate = '2021-01-01'
SET #endDate = '2021-06-30'
;
with d (dt, eom) as (
select #startDate
, convert(int, replace(convert(varchar(10), eomonth(#startDate), 102), '.', ''))
union all
select dateadd(month, 1, dt)
, eomonth(dateadd(month, 1, dt))
from d
where dateadd(month, 1, dt) < #endDate
)
SELECT ProcessDate
, LoanOrigRiskGrade
, SUM(LoanOriginalBalance) AS LoanOrigBalance
, Count(LoanID) as CountofLoanID
FROM SomeTable
inner join d on d.eom = SomeTable.ProcessDate
Difficult to check without sample data.

Add a date range to SQL query

I have simple SQL Server view that I need to make amends to:
CREATE VIEW [dbo].[ApplicantStat]
AS SELECT ISNULL(CONVERT(VARCHAR(50), NEWID()), '') AS Pkid,
AVG(ApplicationTime) AS 'AvgApplicationTime',
AVG(ResponseTime) AS 'AvgResponseTime',
CAST(ROUND(100.0 * count(case when [IsAccepted] = 1 then 1 end) / count(case when [IsValid] = 1 then 1 end), 0) AS int) AS 'AcceptRate'
FROM [Application]
It works as planned, but I need to add a date range to it. It's not quite as simple as Where > this date and < that date, instead I need to create a range.
Suppose I have a 'CreatedOn' date in my Application table. I want to be able to include all rows from the last full day (yesterday) and work back 30 days (inclusive).
I'm using SQL Server 2014.
Use :
where CreatedOn between cast(getdate()-30 as date) and cast(getdate()-1 as date)
Please notice CAST is used, it is because to get the full day ignoring the time part.
Something like this:
where MyColumn between dateadd(dd, -1, convert(date, getdate())) and dateadd(dd, -30, convert(date, getdate()))
It's a bit beyond the scope of this question, but maybe useful to some. I like this way of creating a table with date range, to use in queries:
USE MyDataBase
DECLARE #StartDate DATE
DECLARE #EndDate DATE
SET #StartDate = '2014-01-01' -- << user input >> --
SET #EndDate = '2036-12-31' -- << user input >> --
IF OBJECT_ID ('TEMPDB..#Date') IS NOT NULL DROP TABLE #Date
IF OBJECT_ID ('TEMPDB..#Date') IS NULL CREATE TABLE #Date (DateOne DATE)
INSERT INTO #Date VALUES (#StartDate)
WHILE #StartDate < #EndDate
BEGIN
INSERT INTO #Date
SELECT DATEADD (DD, 1, #StartDate) AS Date
SET #StartDate = DATEADD (DD, 1, #StartDate)
END
SELECT * FROM #Date
You should be able to just stick a WHERE with a BETWEEN clause on the end.
CREATE VIEW [dbo].[ApplicantStat]
AS SELECT ISNULL(CONVERT(VARCHAR(50), NEWID()), '') AS Pkid,
AVG(ApplicationTime) AS 'AvgApplicationTime',
AVG(ResponseTime) AS 'AvgResponseTime',
CAST(ROUND(100.0 * count(case when [IsAccepted] = 1 then 1 end) / count(case when [IsValid] = 1 then 1 end), 0) AS int) AS 'AcceptRate'
FROM [Application]
WHERE CreatedOn BETWEEN GETDATE()-1 AND GETDATE()-30

calculate fiscal year in sql select statement?

I have a date field that needs to return in fiscal year format. example
Start_Date Year
04/01/2012 - 2013
01/01/2012 - 2012
09/15/2013 - 2014
We need to calculate
04/01/2012 to 03/31/2013 is FY 2013
and
04/01/2013 to 03/31/2014 is FY 2014
How can we do that in select statement?
David has a very good solution. A simpler expression is:
select year(dateadd(month, -3, start_date)) as FiscalYear
That is, subtract 3 months and take the year.
EDIT:
As noted in the comment, this seems to produce one year too early. Here are two solutions:
select year(dateadd(month, 9, start_date)) as FiscalYear
select 1 + year(dateadd(month, -3, start_date)) as FiscalYear
SELECT CASE WHEN DatePart(Month, Start_Date) >= 4
THEN DatePart(Year, Start_Date) + 1
ELSE DatePart(Year, Start_Date)
END AS Fiscal_Year
FROM data
I just chose to do it this way. It's easy and you can replace the 09,30 with whatever you want your fiscal year end to be. Not sure if this works in anything but SQL Server though.
CASE
WHEN CAST(GETDATE() AS DATE) >
SMALLDATETIMEFROMPARTS(DATEPART(YEAR,GETDATE()),09,30,00,000)
THEN
DATEPART(YEAR,GETDATE()) + 1 ELSE DATEPART(YEAR,GETDATE())
END AS FY
For Australian financial year, use the following:
SELECT
year(dateadd(MONTH, 6, DateColumn)) AS FY,
...
FROM ...
Assuming that you have a table Fiscal_Year with Start_Date per Year, and you want to find the fiscal year for a given date #Date:
SELECT MIN(Year) WHERE #Date >= Start_Date FROM Fiscal_Year
Declare #t table(StartDate date ,Year1 int)
insert into #t values('04/01/2012',2013),('01/01/2012',2012),('09/15/2013',2014)
;with CTE as
(select max(year1) maxyear from #t)
, cte1 as
(select cast('04/01/'+convert(varchar(4),a.year1) as date) FromFY,dateadd(day,-1,dateadd(year,1,cast('04/01/'+convert(varchar(4),a.year1) as date))) ToFY
,b.year1 from #t a inner join (select min(year1)year1 from #t) b on a.year1=b.year1
union all
select cast(dateadd(day,1,ToFY) as date),cast(dateadd(year,1,ToFY) as date),year1+1 year1 from cte1 where year1<=(select maxyear from cte)
)
select * from cte1
DECLARE #STARTDATE DATETIME, #ENDDATE DATETIME,#CURR_DATE DATETIME
SET #CURR_DATE='2015-01-30'
IF MONTH(#CURR_DATE) IN (1,2,3)
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
END
ELSE
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
END
SELECT #STARTDATE AS ST_FI,#ENDDATE AS END_FY
...something simple :)
(YEAR(DATEADD(Month,-((DATEPART(Month,[Date])+5) %12),[Date]))+) AS Financial_Year
declare #Date smalldatetime, #FiscalYearStartMonth tinyint
set #Date = GETDATE();
set #FiscalYearStartMonth = 1; -- Jan
print convert(varchar(4),
case when MONTH(#Date) < #FiscalYearStartMonth
then YEAR(#Date) -1
else YEAR(#Date) end)
assuming #Date is your [Start_Date] field, you can:
select * from yourTable
group by convert(varchar(4),
case when MONTH([Start_Date]) < #FiscalYearStartMonth
then YEAR([Start_Date]) -1
else YEAR([Start_Date]) end)
Hope this helps
This is what would look like in oracle to get current financial year. Enter the date for which you want to find fiscal year in place of sysdate
SELECT '01-APR-'
||TO_CHAR((add_months(**sysdate**,-3)),'YYYY') FIN_YEAR_START_DATE,
'31-MAR-'
||(TO_CHAR((add_months(**sysdate**,-3)),'YYYY')+1) FIN_YEAR_END_DATE
FROM dual;
For only year format (FY 2020) use following query:
SELECT tender_opening_date,CASE WHEN MONTH( order_date) >= 4
THEN CONCAT('FY ',YEAR(( order_date)) +1 )
ELSE CONCAT('FY ',YEAR( order_date)-1 )
END AS Fiscal_Year
FROM orders_tbl
For full financial Year (FY 2019-20) use following query:
SELECT tender_opening_date,CASE WHEN MONTH( order_date) >= 4
THEN CONCAT('FY ',YEAR( order_date),'-',DATE_FORMAT( order_date,'%y') +1 )
ELSE CONCAT('FY ',YEAR( order_date)-1,'-',DATE_FORMAT( order_date,'%y') )
END AS Fiscal_Year
FROM orders_tbl

SSIS job including SQL which creates temporary table

Have constructed a query which basically looks at a table which contains all bank holidays and then looks at each month for current financial year, then tells me how many working days are available to work minus the bank hols and weekends. For example this month there are 21. There is also a cumulative filed which basically adds up each month so the cumulative for April-Feb will have all those days added.
Within the query there is a CreateTable #DATA which is dropped at the end, this works fine within Management Studio and runs correctly.
My problem is that I am doing an SSIS job and have saved my query as a SQL file and have selected it using the 'Browse' button. It is not allowing me to continue as I believe it has a problem with the temporary table (See screenshot)
Any suggestions on how I can get this to work while maintaining functionality?
Please see code for reference:
DECLARE #StartDate DATETIME,
#EndDate DATETIME
SELECT #StartDate = (select
case when month(getdate()) >= 4 then
convert(datetime, cast(year(getdate()) as varchar) + '-4-1')
else
convert(datetime, cast(year(getdate())-1 as varchar) + '-4-1')
end),
#EndDate = (select
case when month(getdate()) < 4 then
convert(datetime, cast(year(getdate()) as varchar) + '-3-31')
else
convert(datetime, cast(year(getdate())+1 as varchar) + '-3-31')
end)
CREATE TABLE #data
(
firstday DATETIME NOT NULL PRIMARY KEY,
workingdays INT NOT NULL
);
WITH dayscte ([Date])
AS (SELECT #StartDate
UNION ALL
SELECT Dateadd(DAY, 1, [Date])
FROM dayscte
WHERE [Date] <= #Enddate)
INSERT INTO #data
SELECT MIN([Date]),
COUNT(*) [Day]
FROM table2
LEFT JOIN [dbo].[mydb].[mytable1]
ON [Date] BETWEEN [dbo].[mydb].[mytable1].startdate AND [dbo].[mydb].[mytable1].enddate
where
NOT EXISTS (
SELECT field1,field2 FROM [dbo].[mydb].[mytable1].tscheme_cal WHERE
dayid ='0234572347854234'
AND
[date] <= startdate
AND
[date] >= enddate
)
AND Datename(weekday, [Date]) NOT IN ( 'Saturday', 'Sunday' )
GROUP BY Datepart(MONTH, [Date]),
Datepart(YEAR, [Date])
OPTION (MAXRECURSION 366)
DECLARE #Date DATETIME
SET #Date = (SELECT MIN(firstday)
FROM #data)
SELECT Period,
workingdays [Days_Available] ,
year (firstday) AS [Year]
FROM (SELECT Datename(MONTH, firstday) [Period],
workingdays,
0 [SortField],
firstday
FROM #data
UNION
SELECT Datename(MONTH, #Date) + ' - ' + Datename(MONTH, firstday),
(SELECT SUM(workingdays)
FROM #data b
WHERE b.firstday <= a.firstday) [WorkingDays],
1 [SortField],
firstday
FROM #data a
WHERE
firstday > #Date) data
ORDER BY sortfield,
firstday
DROP TABLE #data
its not easy dealing with temp tables on SSIS.
I suggest this article:
http://www.sqllike.com/using-temporary-tables-with-ssis.html
it is a solution, but I don't like it.
I sometimes i use table variables or create a regular table on the DB and then drop it in the end.
In SSIS I find that table variables work well. You can't use temp tables even in a stored proc if it is the source code for a transformation.
In SQL Server 2012 if you use temporary tables you must specify a results set.
This is an issue with the sp_describe_first_result_set procedure that SSIS uses to returns the output metadata.
E.g.
EXEC dbo.RptResults_StoredProcedure
Becomes
EXEC dbo.RptResults_StoredProcedure
WITH RESULT SETS
((
Date NVARCHAR(10),
Location VARCHAR(12),
Department CHAR(1),
Shift CHAR(1),
ForecastSales DECIMAL(18,2),
ActualSales DECIMAL(18,2)
))
For more information view
http://blog.concentra.co.uk/2014/08/22/column-metadata-determined-correctly-ssis-data-flow-task-stored-procedure-inputs/
http://blog.concentra.co.uk/2014/08/22/column-metadata-determined-correctly-ssis-data-flow-task-stored-procedure-inputs/

t-sql select get all Months within a range of years

I need a select to return Month and year Within a specified date range where I would input the start year and month and the select would return month and year from the date I input till today.
I know I can do this in a loop but I was wondering if it is possible to do this in a series selects?
Year Month
---- -----
2010 1
2010 2
2010 3
2010 4
2010 5
2010 6
2010 7
and so on.
Gosh folks... using a "counting recursive CTE" or "rCTE" is as bad or worse than using a loop. Please see the following article for why I say that.
http://www.sqlservercentral.com/articles/T-SQL/74118/
Here's one way to do it without any RBAR including the "hidden RBAR" of a counting rCTE.
--===== Declare and preset some obviously named variables
DECLARE #StartDate DATETIME,
#EndDate DATETIME
;
SELECT #StartDate = '2010-01-14', --We'll get the month for both of these
#EndDate = '2020-12-05' --dates and everything in between
;
WITH
cteDates AS
(--==== Creates a "Tally Table" structure for months to add to start date
-- calulated by the difference in months between the start and end date.
-- Then adds those numbers to the start of the month of the start date.
SELECT TOP (DATEDIFF(mm,#StartDate,#EndDate) + 1)
MonthDate = DATEADD(mm,DATEDIFF(mm,0,#StartDate)
+ (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1),0)
FROM sys.all_columns ac1
CROSS JOIN sys.all_columns ac2
)
--===== Slice each "whole month" date into the desired display values.
SELECT [Year] = YEAR(MonthDate),
[Month] = MONTH(MonthDate)
FROM cteDates
;
I know this is an old question, but I'm mildly horrified at the complexity of some of the answers. Using a CTE is definitely the simplest way to go for selecting these values:
WITH months(dt) AS
(SELECT getdate() dt
UNION ALL
SELECT dateadd(month, -1, dt)
FROM months)
SELECT
top (datediff(month, '2017-07-01' /* start date */, getdate()) + 1)
YEAR(months.dt) yr, MONTH(months.dt) mnth
FROM months
OPTION (maxrecursion 0);
Just slap in whichever start date you'd like in place of the '2017-07-01' above and you're good to go with an efficient and easily-integrated solution.
Edit: Jeff Moden's answer quite effectively advocates against using rCTEs. However, in this case it appears to be a case of premature optimization - we're talking about 10's of records in all likelihood, and even if you span back to 1900 from today, it's still a minuscule hit. Using rCTEs to achieve code maintainability seems to be worth the trade if the expected result set is small.
You can use something like this: Link
To generate the equivalent of a numbers table using date ranges.
But could you please clarify your inputs and outputs?
Do you want to input a start date, for example, '2010-5-1' and end date, for example, '2010-8-1' and have it return every month between the two? Do you want to include the start month and end month, or exclude them?
Here's some code that I wrote that will quickly generate an inclusive result of every month between two dates.
--Inputs here:
DECLARE #StartDate datetime;
DECLARE #EndDate datetime;
SET #StartDate = '2010-1-5 5:00PM';
SET #EndDate = GETDATE();
--Procedure here:
WITH RecursiveRowGenerator (Row#, Iteration) AS (
SELECT 1, 1
UNION ALL
SELECT Row# + Iteration, Iteration * 2
FROM RecursiveRowGenerator
WHERE Iteration * 2 < CEILING(SQRT(DATEDIFF(MONTH, #StartDate, #EndDate)+1))
UNION ALL
SELECT Row# + (Iteration * 2), Iteration * 2
FROM RecursiveRowGenerator
WHERE Iteration * 2 < CEILING(SQRT(DATEDIFF(MONTH, #StartDate, #EndDate)+1))
)
, SqrtNRows AS (
SELECT *
FROM RecursiveRowGenerator
UNION ALL
SELECT 0, 0
)
SELECT TOP(DATEDIFF(MONTH, #StartDate, #EndDate)+1)
DATEADD(month, DATEDIFF(month, 0, #StartDate) + A.Row# * POWER(2,CEILING(LOG(SQRT(DATEDIFF(MONTH, #StartDate, #EndDate)+1))/LOG(2))) + B.Row#, 0) Row#
FROM SqrtNRows A, SqrtNRows B
ORDER BY A.Row#, B.Row#;
Code below generates the values for the range between 21 Jul 2013 and 15 Jan 2014.
I usually use it in SSRS reports for generating lookup values for the Month parameter.
declare
#from date = '20130721',
#to date = '20140115';
with m as (
select * from (values ('Jan', '01'), ('Feb', '02'),('Mar', '03'),('Apr', '04'),('May', '05'),('Jun', '06'),('Jul', '07'),('Aug', '08'),('Sep', '09'),('Oct', '10'),('Nov', '11'),('Dec', '12')) as t(v, c)),
y as (select cast(YEAR(getdate()) as nvarchar(4)) [v] union all select cast(YEAR(getdate())-1 as nvarchar(4)))
select m.v + ' ' + y.v [value_field], y.v + m.c [label_field]
from m
cross join y
where y.v + m.c between left(convert(nvarchar, #from, 112),6) and left(convert(nvarchar, #to, 112),6)
order by y.v + m.c desc
Results:
value_field label_field
---------------------------
Jan 2014 201401
Dec 2013 201312
Nov 2013 201311
Oct 2013 201310
Sep 2013 201309
Aug 2013 201308
Jul 2013 201307
you can do the following
SELECT DISTINCT YEAR(myDate) as [Year], MONTH(myDate) as [Month]
FROM myTable
WHERE <<appropriate criteria>>
ORDER BY [Year], [Month]
---Here is a version that gets the month end dates typically used for accounting purposes
DECLARE #StartDate datetime;
DECLARE #EndDate datetime;
SET #StartDate = '2010-1-1';
SET #EndDate = '2020-12-31';
--Procedure here:
WITH RecursiveRowGenerator (Row#, Iteration)
AS ( SELECT 1, 1
UNION ALL
SELECT Row# + Iteration, Iteration * 2
FROM RecursiveRowGenerator
WHERE Iteration * 2 < CEILING(SQRT(DATEDIFF(MONTH, #StartDate, #EndDate)+1))
UNION ALL SELECT Row# + (Iteration * 2), Iteration * 2
FROM RecursiveRowGenerator
WHERE Iteration * 2 < CEILING(SQRT(DATEDIFF(MONTH, #StartDate, #EndDate)+1)) )
, SqrtNRows AS ( SELECT * FROM RecursiveRowGenerator
UNION ALL SELECT 0, 0 )
SELECT TOP(DATEDIFF(MONTH, #StartDate, #EndDate)+1)
DateAdd(d,-1,DateAdd(m,1, DATEADD(month, DATEDIFF(month, 0, #StartDate) + A.Row# * POWER(2,CEILING(LOG(SQRT(DATEDIFF(MONTH, #StartDate, #EndDate)+1))/LOG(2))) + B.Row#, 0) ))
Row# FROM SqrtNRows A, SqrtNRows B ORDER BY A.Row#, B.Row#;
DECLARE #Date1 DATE
DECLARE #Date2 DATE
SET #Date1 = '20130401'
SET #Date2 = DATEADD(MONTH, 83, #Date1)
SELECT DATENAME(MONTH, #Date1) "Month", MONTH(#Date1) "Month Number", YEAR(#Date1) "Year"
INTO #Month
WHILE (#Date1 < #Date2)
BEGIN
SET #Date1 = DATEADD(MONTH, 1, #Date1)
INSERT INTO #Month
SELECT DATENAME(MONTH, #Date1) "Month", MONTH(#Date1) "Month Number", YEAR(#Date1) "Year"
END
SELECT * FROM #Month
ORDER BY [Year], [Month Number]
DROP TABLE #Month
declare #date1 datetime,
#date2 datetime,
#date datetime,
#month integer,
#nm_bulan varchar(20)
create table #month_tmp
( bulan integer null, keterangan varchar(20) null )
select #date1 = '2000-01-01',
#date2 = '2000-12-31'
select #month = month(#date1)
while (#month < 13)
Begin
IF #month = 1
Begin
SELECT #date = CAST( CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,0,#date1))-1),DATEADD(mm,0,#date1)),111) + ' 00:00:00' as DATETIME )
End
ELSE
Begin
SELECT #date = CAST( CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,#month -1,#date1))-1),DATEADD(mm,#month -1,#date1)),111) + ' 00:00:00' as DATETIME )
End
select #nm_bulan = DATENAME(MM, #date)
insert into #month_tmp
select #month as nilai, #nm_bulan as nama
select #month = #month + 1
End
select * from #month_tmp
drop table #month_tmp
go