Sqlserver in 实现 参数化查询 XML类型解决方案

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;
    }

来源:http://www.cnblogs.com/tangruixin/archive/2012/04/23/2465917.html

你可能感兴趣的:(sql,oracle)