原文地址:html
http://www.cnblogs.com/lzrabbit/archive/2012/04/22/2465313.htmlsql
除了校驗參數內容,過濾長度和sql關鍵字。性能
解決in條件拼接字符串spa
comm.CommandText = "select * from Users(nolock) where UserID in (@UserID1,@UserId2,@UserID3,@UserID4)"; comm.Parameters.AddRange( new SqlParameter[]{ new SqlParameter("@UserID1", SqlDbType.Int) { Value = 1}, new SqlParameter("@UserID2", SqlDbType.Int) { Value = 2}, new SqlParameter("@UserID3", SqlDbType.Int) { Value = 3}, new SqlParameter("@UserID4", SqlDbType.Int) { Value = 4} });
文章導讀code
使用CHARINDEX或like實現where in 參數化xml
使用exec動態執行SQl實現where in 參數化htm
身爲一名小小的程序猿,在平常開發中不能夠避免的要和where in和like打交道,在大多數狀況下咱們傳的參數很少簡單作下單引號、敏感字符轉義以後就直接拼進了SQL,執行查詢,搞定。如有一天你不可避免的須要提升SQL的查詢性能,須要一次性where in 幾百、上千、甚至上萬條數據時,參數化查詢將是必然進行的選擇。然而如何實現where in和like的參數化查詢,是個讓很多人頭疼的問題。
首先說一下咱們經常使用的辦法,直接拼SQL實現,通常狀況下都能知足須要
string userIds = "1,2,3,4"; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = string.Format("select * from Users(nolock) where UserID in({0})", userIds); comm.ExecuteNonQuery(); }
須要參數化查詢時進行的嘗試,很顯然以下這樣執行SQL會報錯錯誤
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "select * from Users(nolock) where UserID in(@UserID)"; comm.Parameters.Add(new SqlParameter("@UserID", SqlDbType.VarChar, -1) { Value = "1,2,3,4" }); comm.ExecuteNonQuery(); }
很顯然這樣會報錯誤:在將 varchar 值 '1,2,3,4' 轉換成數據類型 int 時失敗,由於參數類型爲字符串,where in時會把@UserID當作一個字符串來處理,至關於實際執行了以下語句
select * from Users(nolock) where UserID in('1,2,3,4')
若執行的語句爲字符串類型的,SQL執行不會報錯,固然也不會查詢出任何結果
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "select * from Users(nolock) where UserName in(@UserName)"; comm.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, -1) { Value = "'john','dudu','rabbit'" }); comm.ExecuteNonQuery(); }
這樣不會抱任何錯誤,也查不出想要的結果,由於這個@UserName被當作一個字符串來處理,實際至關於執行以下語句
select * from Users(nolock) where UserName in('''john'',''dudu'',''rabbit''')
由此相信你們對於爲什麼簡單的where in 傳參沒法獲得正確的結果知道爲何了吧,下面咱們來看一看如何實現正確的參數化執行where in,爲了真正實現參數化where in 傳參,不少淫纔想到了各類替代方案
方案1,使用CHARINDEX或like 方法實現參數化查詢,毫無疑問,這種方法成功了,並且成功的複用了查詢計劃,但同時也完全的讓查詢索引失效(在此不探討索引話題),形成的後果是全表掃描,若是表裏數據量很大,百萬級、千萬級甚至更多,這樣的寫法將形成災難性後果;若是數據量比較小、只想藉助參數化實現防止SQL注入的話這樣寫也無可厚非,仍是得看具體需求。(不推薦)
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; //使用CHARINDEX,實現參數化查詢,能夠複用查詢計劃,同時會使索引失效 comm.CommandText = "select * from Users(nolock) where CHARINDEX(','+ltrim(str(UserID))+',',','+@UserID+',')>0"; comm.Parameters.Add(new SqlParameter("@UserID", SqlDbType.VarChar, -1) { Value = "1,2,3,4" }); comm.ExecuteNonQuery(); } using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; //使用like,實現參數化查詢,能夠複用查詢計劃,同時會使索引失效 comm.CommandText = "select * from Users(nolock) where ','+@UserID+',' like '%,'+ltrim(str(UserID))+',%' "; comm.Parameters.Add(new SqlParameter("@UserID", SqlDbType.VarChar, -1) { Value = "1,2,3,4" }); comm.ExecuteNonQuery(); }
方案2 使用exec動態執行SQL,這樣的寫法毫無疑問是很成功的,並且代碼也比較優雅,也起到了防止SQL注入的做用,看上去很完美,不過這種寫法和直接拼SQL執行沒啥實質性的區別,查詢計劃沒有獲得複用,對於性能提高沒任何幫助,很有種脫了褲子放屁的感受,但也不失爲一種解決方案。(不推薦)
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; //使用exec動態執行SQL
//實際執行的查詢計劃爲(@UserID varchar(max))select * from Users(nolock) where UserID in (1,2,3,4)
//不是預期的(@UserID varchar(max))exec('select * from Users(nolock) where UserID in ('+@UserID+')')
comm.CommandText = "exec('select * from Users(nolock) where UserID in ('+@UserID+')')"; comm.Parameters.Add(new SqlParameter("@UserID", SqlDbType.VarChar, -1) { Value = "1,2,3,4" }); comm.ExecuteNonQuery(); }
方案3 爲where in的每個參數生成一個參數,寫法上比較麻煩些,傳輸的參數個數有限制,最多2100個,能夠根據須要使用此方案(推薦)
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; //爲每一條數據添加一個參數 comm.CommandText = "select * from Users(nolock) where UserID in (@UserID1,@UserId2,@UserID3,@UserID4)"; comm.Parameters.AddRange( new SqlParameter[]{ new SqlParameter("@UserID1", SqlDbType.Int) { Value = 1}, new SqlParameter("@UserID2", SqlDbType.Int) { Value = 2}, new SqlParameter("@UserID3", SqlDbType.Int) { Value = 3}, new SqlParameter("@UserID4", SqlDbType.Int) { Value = 4} }); comm.ExecuteNonQuery(); }
方案4 使用臨時表實現(也可使用表變量性能上可能會更加好些),寫法實現上比較繁瑣些,能夠根據須要寫個通用的where in臨時表查詢的方法,以供不時之需,我的比較推崇這種寫法,可以使查詢計劃獲得複用並且對索引也能有效的利用,不過因爲須要建立臨時表,會帶來額外的IO開銷,若查詢頻率很高,每次的數據很少時仍是建議使用方案3,若查詢數據條數較多,尤爲是上千條甚至上萬條時,強烈建議使用此方案,能夠帶來巨大的性能提高(強烈推薦)
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; string sql = @" declare @Temp_Variable varchar(max) create table #Temp_Table(Item varchar(max)) while(LEN(@Temp_Array) > 0) begin if(CHARINDEX(',',@Temp_Array) = 0) begin set @Temp_Variable = @Temp_Array set @Temp_Array = '' end else begin set @Temp_Variable = LEFT(@Temp_Array,CHARINDEX(',',@Temp_Array)-1) set @Temp_Array = RIGHT(@Temp_Array,LEN(@Temp_Array)-LEN(@Temp_Variable)-1) end insert into #Temp_Table(Item) values(@Temp_Variable) end select * from Users(nolock) where exists(select 1 from #Temp_Table(nolock) where #Temp_Table.Item=Users.UserID) drop table #Temp_Table"; comm.CommandText = sql; comm.Parameters.Add(new SqlParameter("@Temp_Array", SqlDbType.VarChar, -1) { Value = "1,2,3,4" }); comm.ExecuteNonQuery(); }
like參數化查詢
like查詢根據我的習慣將通配符寫到參數值中或在SQL拼接均可,兩種方法執行效果同樣,在此不在詳述
using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; //將 % 寫到參數值中 comm.CommandText = "select * from Users(nolock) where UserName like @UserName"; comm.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, 200) { Value = "rabbit%" }); comm.ExecuteNonQuery(); } using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; //SQL中拼接 % comm.CommandText = "select * from Users(nolock) where UserName like @UserName+'%'"; comm.Parameters.Add(new SqlParameter("@UserName", SqlDbType.VarChar, 200) { Value = "rabbit%" }); comm.ExecuteNonQuery(); }
看到Tom.湯和蚊子額的評論 補充了下xml傳參和tvp傳參,並對6種方案作了個簡單總結