2015-08-30 72 views
0

我有表T1ID1,ID2SQL Server:選擇「值或全部」

我需要寫一個「選擇」存儲過程是這樣

Create SP_GetT1ByID1AndID2 
    @id1 varchar(50), @id2 varchar(50) 
as 
begin 
    Select * 
    from T1 
    where 
     // If (ID1 = "All" and ID2 = "All") so we have to return all the data in the table T1 
     // If (ID1 = "All" and ID2 != "All") so we have filter the data according to ID2 
     // If (ID1 != "All" and ID2 = "All") so we have filter the data according to ID1 
     // If (ID1 != "All" and ID2 != "All") so we have filter the data according to ID1 and ID2 
end 
+1

旁註:你應該** **不使用'sp_'前綴爲您的存儲過程。微軟[留作自己使用前綴(見*命名存儲過程*)(http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),和你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也是不利的](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! –

回答

0
select * from your_table 
where (@id1 = 'All' or ID1 = @id1) 
    and (@id2 = 'All' or ID2 = @id2)