簡單實現多條件查詢 by hyw

來源:互聯網
上載者:User

       我們在開發過程中,特別是資料庫系統的開發中經常會遇到多條件的查詢狀況。例如:查詢某一個部門某個時間段的車輛費用支出,這就涉及到多條件查詢。其實多條件查詢的方法有很多種,有些寫法是比較煩瑣,效率也不高,比如一個條件一個條件去if—else判斷拼湊sql語句。我在這裡使用一種個人覺得寫法簡單,理解也比較簡單的方法:
  CREATE PROCEDURE [dbo].[usp_GetFeeInfo]
             @Number nvarchar(50) = null, --車牌號
             @Unit nvarchar(50) = null, --部門
             @FeeType nvarchar(50) = null, --費用類型
             @StartDate datetime = null, --查詢的起始時間
             @EndDate datetime = null  --查詢的結束時間
AS
BEGIN
 select  f.ID,
   f.Number,
   f.[Type],
   f.FeeDate,
   round(f.[Money],2) as [Money],
   f.Status,
   f.Memo,
   c.id as cid,
   c.unit1
 from Fee f left join Car c
 on f.Number = c.Number
 where (f.Number = @Number or @Number is null)  --如果@Number參數為null的話那表示這個欄位不在查詢的條件中;這可以在程式裡簡單的實現。
  and (c.unit1 = @Unit or @Unit is null)
  and (f.[type] = @FeeType or @FeeType is null)
  and (f.Feedate >= @StartDate or @StartDate is null)
  and (f.Feedate <= @EndDate or @EndDate is null)
 order by f.FeeDate desc
END

程式裡面你只要把所有查詢條件的值都錄入進去。
例如:如果為“全部”的話,那就把這個欄位的值設定為:null

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.