简体   繁体   中英

How to get fiscal year in a stored procedure?

I have a stored procedure and from the c# code the 'serverdate' is passed to the SP.serverdate is the value of System.Datetime.now().

How can i find the fiscal year from that serverdate in sp?

The fiscal year is taken as "April 1 to March 31".

SELECT 
    CASE 
    WHEN DATEPART(month, GETDATE()) >= 4 THEN 
        CAST(DATEPART(year, GETDATE()) AS VARCHAR(4)) + '-' + CAST(DATEPART(year, GETDATE())+1 AS VARCHAR(4))
    ELSE 
        CAST(DATEPART(year, GETDATE())-1 AS VARCHAR(4)) + '-' + CAST(DATEPART(year, GETDATE()) AS VARCHAR(4))
    END AS fiscal

Is that the kind of thing you're looking for?

These are Oracle queries but they will work in SQL SERVER if you select from your table or SQL SERVER system table such as "dual" in Oracle:

SELECT start_date, Add_Months(start_date-1, 12) end_date
  FROM
 (
  SELECT Add_Months(Trunc(SYSDATE, 'YY'), 3) start_date
    FROM dual
 )
 /

Output:

Start_Date  End_Date
-------------------------
4/1/2013    3/31/2014

Fiscal Year - Annual table "on the fly":

SELECT (start_date-1)+ LEVEL  Fiscal_Year
  FROM
(
  SELECT start_date, Add_Months(start_date-1, 12) end_date
    FROM
  (
   SELECT Add_Months(Trunc(SYSDATE, 'YY'), 3) start_date
     FROM dual
  )
)
CONNECT BY LEVEL <= (end_date+1)-start_date
/

Output:

FISCAL_YEAR
------------
4/1/2013
4/2/2013
4/3/2013
....
....
3/31/2014

If you are working around SYSDATE then:

select CASE
         when substr(to_char(SYSDATE, 'ddmmyyyy'), 3, 2) IN
              ('01', '02', '03') THEN
          substr(to_char(add_months(SYSDATE, -12), 'ddmmyyyy'), 5, 4)
         else
          substr(to_char(SYSDATE, 'ddmmyyyy'), 5, 4)
       END
  from dual;

If you want to go for any random date,change to ddmmyyyy format.Below is for a sample date:

 select case 
when substr('17012014' ,3,2) in ('01','02','03') then SUBSTR(TO_CHAR(ADD_MONTHS(TO_DATE('17012014','ddmmyyyy'),-12),'ddmmyyyy'),5,4)

else
substr(to_char(to_date('17012014','ddmmyyyy'),'ddmmyyyy'),5,4)
end
 from DUAL; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM