1:如果 参数 是int 类型 : declare @a xml set @a=' rowid1/id/row rowid5/id/row rowid4/id/row rowid3/id/row rowid2/id/row' select * from product where id in ( select d.x.value('./id[1]','int') from @a.nodes('/*') as d(x)) 2:如果 参数 是var
1:如果 参数 是int 类型 :
declare @a xml
set @a='
1
5
4
3
2 '
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='
a
b5
c4
d3
e2 '
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( " {0} " ,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; }
如果认为是好文的请不要吝啬您的推荐,写个文章不容易。
查看更多关于Sqlserverin实现参数化查询XML类型解决方案的详细内容...