Newbie - simple Query Question - function

  • I want to get the financial Year for a date. I have this:

    (Year(DateAdd("m",-3,[MyDate]))) + ' - ' + (Year(DateAdd("m",9,[MyDate])))AS financial_year

    But it doesnt work - it adds them together instead of:

    2016 - 2017
    Each part works correctly until I put them together

  • If you want YYYY - YYYY then you have to cast the Years as strings, otherwise, T-SQL will interpret the + as the addition operator. Check out CAST()

  • SOLVED-
    convert(varchar(4),(Year(DateAdd("m",-3,[myDate])))) + ' - ' + convert(varchar(4), (Year(DateAdd("m",9,[myDate])))) AS financial_year

  • Recommend you use CHAR(4) instead of VARCHAR(4).  Right sizing and using the right datatype is a good habit to get into.  VARCHAR(4) actually takes 6 bytes (4 for data, 2 to identify the size of the data).  It may not matter on one or two rows but it will when you start doing some heavy lifting.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply