• Why not just do (using the function definition and parameters (and the @firstDate variable) as given):

    set @firstDate = dateadd(dd,1-datepart(dd,@inputdate) ,@inputDate) -- ensures that we start with the first of the month

    select

    dateadd(wk, @occurAt - 1, -- adds the additional weeks, if any

    dateadd(dd, @day - datepart(dw, @firstDate)-- moves to the given day of week

    + case when @day < datepart(dw, dateadd(dd,1-datepart(dd,@firstdate) ,@firstDate)) then 7 else 0 end, -- ensures we don't go back to the last month

    @firstDate

    )

    )