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; }
如果認為是好文的請不要吝嗇您的推薦,寫個文章不容易。