Re: [問題] sqlcommand中parameter的用法
看板C_Sharp (C#)作者TeemingVoid (TeemingVoid)時間13年前 (2011/12/29 20:12)推噓1(1推 0噓 1→)留言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
12/30 23:47, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章
-50
111