Nu prea înţeleg ce ceri... poţi să faci:
WHERE (CASE WHEN a=b THEN c ELSE d END)=e
De exemplu, considerând tabela Employees din Northwind:
EmployeeID |
LastName |
FirstName |
Title |
City |
1 |
Davolio |
Nancy |
Sales Representative |
Seattle |
2 |
Fuller |
Andrew |
Vice President, Sales |
Tacoma |
3 |
Leverling |
Janet |
Sales Representative |
Kirkland |
4 |
Peacock |
Margaret |
Sales Representative |
Redmond |
5 |
Buchanan |
Steven |
Sales Manager |
London |
6 |
Suyama |
Michael |
Sales Representative |
London |
7 |
King |
Robert |
Sales Representative |
London |
8 |
Callahan |
Laura |
Inside Sales Coordinator |
Seattle |
9 |
Dodsworth |
Anne |
Sales Representative |
London |
Să presupunem că vrei să selectezi cu condiţia ca City='London' dacă Title='Sales Representative', însă dacă e alt Title, vrei să pui condiţia City='Seattle', deci să selectezi rândurile care sunt scrise cu italic mai sus.
În acest caz, NU poţi să scrii:
WHERE CASE WHEN Title='Sales Representative' THEN City='London' ELSE City='Seattle' END
Ci trebuie să spui:
WHERE CASE WHEN Title='Sales Representative' THEN 'London' ELSE 'Seattle' END=City
sau, mai clar:
WHERE (Title='Sales Representative' AND City='London') OR (Title<>'Sales Representative' AND City='Seattle')
(de fapt aici ar fi trebuit să scriem "ISNULL(Title,'')<>...", pt. ca expresia să fie echivalentă cu cea de mai sus, însă dacă presupunem că Title nu permite NULL-uri, nu ar fi nevoie)
sau, mai complicat:
WHERE CASE WHEN Title='Sales Representative' THEN
CASE WHEN City='London' THEN 1 ELSE 0 END
ELSE
CASE WHEN City='Seattle' THEN 1 ELSE 0 END
END=1
Răzvan