Sqlserver in 实现 参数化查询 XML类型解决方案
1:如果参数是int类型:
declare @a xml
set @a='
<row><id>1</id></row>
<row><id>5</id></row>
<row><id>4</id></row>
<row><id>3</id></row>
<row><id>2</id></row>'
select * from product where id in (
select d.x.value('./id[1]','int') from @a.nodes('/*') as d(x))
2:如果参数是varchar类型:
declare @a xml
set @a='
<row><name>a</name></row>
<row><name>b5</name></row>
<row><name>c4</name></row>
<row><name>d3</name></row>
<row><name>e2</name></row>'
select * from product where pname in (
select d.x.value('./name[1]','varchar(100)') from @a.nodes('/*') as d(x))
以第一个为例写的C#简单方法
public DataSet GetData(List<int> idList) { System.Text.StringBuilder idXML = new System.Text.StringBuilder(); // 把IdList转换成idxml(后面要用到的xml参数的值) foreach (var item in idList) { idXML.AppendFormat("<row><id>{0}</id></row>",item); } System.Text.StringBuilder strSql = new System.Text.StringBuilder(); strSql.Append("select * from product where id in ("); // 解析xml参数@a 取出ID 这里可以认为@a是一个特殊的表 strSql.Append("select d.x.value('./id[1]','int') from @a.nodes('/*') as d(x)"); strSql.Append(")"); SqlConnection con = new SqlConnection("数据库连接字符串"); SqlCommand cmd = new SqlCommand(strSql.ToString(), con); // 参数赋值 SqlParameter[] para = new SqlParameter[]{ new SqlParameter("@a",SqlDbType.Xml){Value= idXML.ToString()} }; cmd.Parameters = para; // 查询 SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); sda.Fill(ds); return ds; }
如果认为是好文的请不要吝啬您的推荐,写个文章不容易。