在循环中查询SQL服务器表 [英] Query SQL server Table in a loop

查看:71
本文介绍了在循环中查询SQL服务器表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有这张桌子



Table_Items



Item_ id ---项目

1 --------- a

1 -------- -b

1 --------- c

1 --------- d

2- -------- e

2 --------- f

3 --------- g

4 --------- h





如何循环浏览此列表并获得结果像这样的东西;



商品ID和该ID的所有商品。



例如,1, a,b,c,d

2,e,f

3,g

4,h

解决方案

 选择 Item_ id,
stuff(( SELECT distinct ' ,' + cast(Item as varchar 10 ))
FROM Table_Items t2
其中 t2.Item_ id = t1.Item_ id
FOR XML PATH('' ')), 1 1 ' ' as Item
来自 Table_Items t1
group by Item_ id


  //  如果从sql表中获取所有数据到DataTabl dt; 然后使用此逻辑  
// 否则使用解决方案1 ​​

DataTable dt = new DataTable();
string item_id = string .Empty;
DataRow [] datarows = dt.Select( item_id =' + item_id + < span class =code-string>
');

string result = item_id;

foreach (DataRow dr in datarows)
{
result + = + dr [ 项目]。ToString();
}

// 您可以使用结果;
// TODO:
Console.WriteLine(result);


Hi,

I have this table

Table_Items

Item_ id---Item
1---------a
1---------b
1---------c
1---------d
2---------e
2---------f
3---------g
4---------h


How can i loop through this list and get results something like this;

item id and all items for that ID.

for example, 1,a,b,c,d
2,e,f
3,g
4,h

解决方案

select Item_ id,
  stuff((SELECT distinct ', ' + cast(Item as varchar(10))
           FROM Table_Items t2
           where t2.Item_ id= t1.Item_ id
           FOR XML PATH('')),1,1,'') as Item
from Table_Items t1
group by Item_ id


// if you fetch all data from sql table into DataTabl dt; then use this logic 
//otherwise use Solution 1 

            DataTable dt = new DataTable();
            string item_id = string.Empty;
            DataRow[] datarows =  dt.Select("item_id = '" + item_id + "'");

            string result = item_id;

            foreach (DataRow dr in datarows)
            {
                result += "," + dr["Item"].ToString();
            }

            //you can use result;
            //TODO:
            Console.WriteLine(result);


这篇关于在循环中查询SQL服务器表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆