SqlServer where in 、where like参数化查询问题(转载)


转载来源:https://www.cnblogs.com/lzrabbit/archive/2012/04/22/2465313.html

身为一名小小的程序猿,在日常开发中不可以避免的要和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''')

Sql Server参数化查询之where in和like实现之xml和DataTable传参