作者Arim (Arim5566)
看板C_Sharp
標題[問題] sqlcommand中parameter的用法
時間Thu Dec 29 16:36:19 2011
各位版友好
假設目前我有四個欄位(四個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輸入情形?
謝謝各位版友
--
~宅男的四個徵兆~
∠□ ○ ! * \○/ ★ (○ ?
╦╦└□ " ○□═ □ □>
║║√√ ╦══╦ ∥ |\
一回家就上PTT 每天想正妹 以當好人為樂 忘記正妹虧欠自己
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.32.197.57
→ ssccg:先判斷有沒有輸入值,再產生command text? 12/29 18:30
→ Arim:目前也只能用樓上的方法 只是不知道還有沒有更簡潔的寫法 12/29 18:53
→ DeepSix:反正是符合其中一個以上的狀態才回傳,用or就好啦 12/29 23:44
推 Elly:這要考的是你sql功力吧~用(@xxx='' or xxx=@xxx)處理吧 12/31 10:33