Extended version of where used query for SQL Server