• Here is a maintainable version...

    DECLARE

    @dt datetime,

    @DayOneDayOfWeek int,

    @DaysInMonth int,

    @s-2 varchar(200),

    @crlf varchar(2)

    ;

    SET @dt = '20130401';

    SET @crlf = char(13) + char(10);

    -- get max days in month: calculate first day of the next month and subtract one day

    SET @DaysInMonth = (select datepart(day, dateadd(day, -1, dateadd(month, 1, cast(convert(varchar(8), @dt, 121)+'01' as datetime)))));

    -- need to know day one weekday

    SET @DayOneDayOfWeek = (select DatePart(WeekDay, cast(convert(varchar(8), @dt, 121)+'01' as datetime)));

    -- build day numbers string and pad for first day

    SET @s-2 = REPLACE(SUBSTRING(' << January YEAR >> << February YEAR >> << March YEAR >> << April YEAR >> << May YEAR >> << June YEAR >> << July YEAR >> << August YEAR >> << September YEAR >> << October YEAR >> << November YEAR >> << December YEAR >>', (DatePart(month, @dt) - 1) * 21 + 1, 21), 'YEAR', cast(DatePart(year, @dt) as varchar(4)))

    + ' Su Mo Tu We Th Fr Sa'

    + replicate(' ', @DayOneDayOfWeek - 1)

    + left(' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31', @DaysInMonth * 3)

    ;

    -- Format for display by removing leading space and adding CRLF for each line.

    print

    SUBSTRING(@s, 2, 20)

    + @crlf + SUBSTRING(@s, 23, 20)

    + @crlf + SUBSTRING(@s, 44, 20)

    + @crlf + SUBSTRING(@s, 65, 20)

    + @crlf + SUBSTRING(@s, 86, 20)

    + @crlf + SUBSTRING(@s, 107, 20)

    + @crlf + SUBSTRING(@s, 128, 20)

    + case when len(@s) > 149 then @crlf + SUBSTRING(@s, 149, 20) else '' end

    ;