婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > SqlServer參數化查詢之where in和like實現詳解

SqlServer參數化查詢之where in和like實現詳解

熱門標簽:西安青牛防封電銷卡 威海智能語音外呼系統 400電話申請需要開戶費嗎 重慶防封電銷機器人供應商 智能語音外呼系統哪個牌子好 北京辦理400電話多少 山西語音外呼系統價格 南京電銷外呼系統運營商 溫州語音外呼系統代理
身為一名小小的程序猿,在日常開發中不可以避免的要和where in和like打交道,在大多數情況下我們傳的參數不多簡單做下單引號、敏感字符轉義之后就直接拼進了SQL,執行查詢,搞定。若有一天你不可避免的需要提高SQL的查詢性能,需要一次性where in 幾百、上千、甚至上萬條數據時,參數化查詢將是必然進行的選擇。然而如何實現where in和like的參數化查詢,是個讓不少人頭疼的問題。

where in 的參數化查詢實現

首先說一下我們常用的辦法,直接拼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種方案做了個簡單總結

Sql Server參數化查詢之where in和like實現之xml和DataTable傳參

此文章屬懶惰的肥兔原創
您可能感興趣的文章:
  • SQLServer中使用擴展事件獲取Session級別的等待信息及SQLServer 2016中Session級別等待信息的增強
  • sqlserver 模糊查詢常用方法
  • SqlServer使用 case when 解決多條件模糊查詢問題
  • SqlServer中模糊查詢對于特殊字符的處理方法
  • MSSQL Server 查詢優化方法 整理
  • sqlserver 中charindex/patindex/like 的比較
  • SqlServer參數化查詢之where in和like實現之xml和DataTable傳參介紹
  • SqlServer2016模糊匹配的三種方式及效率問題簡析

標簽:新余 金昌 河源 宜春 貸款群呼 黃山 濟寧 中衛

巨人網絡通訊聲明:本文標題《SqlServer參數化查詢之where in和like實現詳解》,本文關鍵詞  SqlServer,參數,化,查詢,之,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《SqlServer參數化查詢之where in和like實現詳解》相關的同類信息!
  • 本頁收集關于SqlServer參數化查詢之where in和like實現詳解的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 蒲城县| 九江县| 万年县| 迭部县| 玉屏| 武陟县| 泌阳县| 绵阳市| 稻城县| 宁蒗| 耿马| 尼勒克县| 巴彦县| 高唐县| 佛学| 永平县| 会同县| 红桥区| 手机| 新平| 连云港市| 通河县| 乐山市| 营口市| 北海市| 西丰县| 张家港市| 峨眉山市| 闽侯县| 溧水县| 深泽县| 长岛县| 丰城市| 辽中县| 安远县| 托里县| 通江县| 江都市| 广德县| 浙江省| 靖州|