Re: [問題] sqlcommand中parameter的用法

看板C_Sharp (C#)作者 (TeemingVoid)時間13年前 (2011/12/29 20:12), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《Arim (Arim5566)》之銘言: : 各位版友好 : 假設目前我有四個欄位(四個textbox,分別是cid、cname、tel、city) : SqlCommand cmd = new SqlCommand( : "select * from Client where cid=@cid and cname=@cname and : tel=@tel and city=@city", conn); : cmd.Parameters.Add("@cname", SqlDbType.NVarChar, 50).Value = : CnameTextBox.Text; : ... : 上述的sql指令會從資料庫撈回符合這四個欄位的資料回來 : 但是我如果全部的欄位沒有輸入,只輸入部分的欄位(例如只輸入cid) : 他就會回傳符合cid這個欄位的資料 : 但是這樣我就要重複寫sql command,如下 : select * from Client where cid=@cid : 但是目前有四個欄位,我就必須寫入2^4=16條sqlcommand,會非常麻煩 : 請問如何只寫一條sqlcommand,並且可以處理所有的textbox輸入情形? 我使用的是一個有點笨但寫法一致的作法,請參考看看: SQLCommnad 的 CommandText 屬性是: select * from Client where (cid = @cid or @cid = '') and (cname = @cname or @cname = '') and (tel = @tel or @tel = '') and (city = @city or @city = '')" cmd.Parameters.Add("@cname", SqlDbType.NVarChar, 50).Value = CnameTextBox.Text.Trim(); // 繼續加入其他三個參數物件 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.252.120.221

12/30 14:37, , 1F
謝謝 我會參考看看的
12/30 14:37, 1F

12/30 23:47, , 2F
用where (1=1) and 非空才加入 and 非空才加入
12/30 23:47, 2F
文章代碼(AID): #1E_5b7nT (C_Sharp)
討論串 (同標題文章)
文章代碼(AID): #1E_5b7nT (C_Sharp)