Home Forums SQL Server 2008 T-SQL (SS2K8) help me i need dynamic sql query for this code to update dynamically every year RE: help me i need dynamic sql query for this code to update dynamically every year

  • Given the recent post at http://www.sqlservercentral.com/Forums/Topic1689004-392-1.aspx, I take it you still need a handl with the fiscal years. You could encapsulate the logic into a function that returns both the calendar and fiscal year information, which you could then use elsewhere. If the rules change, your updates would be limited to one location. Here's a start at the function, which uses Chris's solution above to determine the fiscal year, plus Lynn's always-useful date functions at http://www.sqlservercentral.com/blogs/lynnpettis/2009/03/25/some-common-date-routines/.

    if OBJECT_ID('dbo.YearInfo', 'if') is not null drop function dbo.YearInfo;

    go

    CREATE FUNCTION dbo.YearInfo(@dtm Datetime) RETURNS TABLE WITH SCHEMABINDING

    AS

    RETURN (

    SELECT CalendarYearStart = DATEADD(year, DATEDIFF(year, 0, @dtm), 0),

    CalendarYearEnd = DATEADD(ms, -3, DATEADD(year, DATEDIFF(year, 0, @dtm) + 1, 0)),

    FiscalYear = YEAR(DATEADD(DAY, 184, @dtm))

    );

    go

    You could add in whatever else you need to know and then use it to select the columns you need.

    SELECT CalendarYearStart, CalendarYearEnd, FiscalYear FROM dbo.YearInfo('06/04/2015');

    SELECT CalendarYearStart, CalendarYearEnd, FiscalYear FROM dbo.YearInfo('07/04/2015');

    Better yet, this can be used in a CROSS APPLY in your query to return the columns based on a datetime column that determines what year the transaction was in.