2010-10-11 145 views
0

我需要過濾的SQL查詢結果,根據3個條件:
1.位置
2.醫生姓名
3.專業名稱SQL語句過濾結果

下面是SQL查詢,如果所有的3個條件不是空的:

if (location != "" && doctor!="" && specialty!="") 

select Location, ... 
from clinicdoctors 
where Location = @Location and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName 

} 

如果只有位置是空的,

if (location == "" && doctor!="" && specialty!="") 
select Location, ... 
from clinicdoctors 
where Location is not null and DoctorName = @DoctorName and SpecialtyName = @SpecialtyName 

... 

如果我想檢查所有的條件,我需要寫八個if語句。 在這種情況下我應該怎麼做來簡化代碼?

+0

是SQL Server查詢? – anishMarokey 2010-10-11 03:55:50

+0

是的,它是sql服務器查詢 – Billy 2010-10-11 03:59:19

回答

0

我認爲在代碼中執行此操作比使用sql做得更好。沒有真正周圍沒有任何辦法,因爲查詢是如此不同,但簡潔的方式做到這一點是:

$loc_where = empty($loc) ? 'Location IS NOT NULL' : "Location = $loc"; 
$doc_where = empty($doc) ? 'AND DoctorName IS NOT NULL' : "AND DoctorName = $doc"; 
$spec_where = empty($spec) ? 'AND SpecialtyName IS NOT NULL' : "AND SpecialtyName = $spec"; 

query ... WHERE $loc_where $doc_where $spec_where 
2
select Location, ... 
from clinicdoctors 
where 
ISNULL(@Location,Location) = Location 
and ISNULL(@DoctorName,DoctorName) = DoctorName 
and ISNULL(@SpecialtyName,SpecialtyName) = SpecialtyName 
+0

調查ISNULL關鍵字。 – 2010-10-11 04:45:13

+0

哎呦。是啊。這會更好。 – Jonn 2010-10-11 04:51:34

+0

如果'location','doctorname'或'specialtyname'爲NULL,那麼這將不起作用 – 2010-10-11 05:19:01