T-SQL refactoring