refactored mssql and db2 query