Sqlserver in 實現 參數化查詢 XML類型

原文: http://www.cnblogs.com/tangruixin/archive/2012/04/23/2465917.htmlhtml

1:若是參數是int類型:node

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類型:ui

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))spa

 

以第一個爲例寫的C#簡單方法code

複製代碼
    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;
    }
複製代碼
相關文章
相關標籤/搜索