Fixed broken query for MS SQL