使用C#在SQL中循环遍历列(并将其值与变量进行比较)

时间:2016-07-18 14:47:07

标签: c# sql sql-server

我有一个大表,它有一个ID列,包含请求/票证信息。

在win表单上,我想让用户输入他的请求ID并以新的形式获取所有请求信息。

我遇到问题的地方是如何遍历一列的值。

以下是我在其他地方看到的并尝试实现[我的数据表名称为st]:

DataTable dt = new DataTable("dbo.table_submission");
DataRow[] foundRows = dt.Select("ID =" + i);
        if (foundRows != null )
        {
            Status status = new Status();
            status.Show();
        }

1 个答案:

答案 0 :(得分:2)

DataTable有Select method,可以为您检索匹配的行,而无需使用显式循环。

例如,假设您要搜索的值位于名为RequestID

的列中
int yourValueToSearch = 1;

DataRows[] foundRows = dt.Select("RequestID = " + yourValueToSearch);
if(foundRows != null && foundRows.Length > 0)
{
    DataTable result = foundRows.CopyToDataTable();
    // Pass the result table to your form....

}

这也可以是字符串,但您需要添加适当的引用

string yourValueToSearch = "ABC123";
DataRows[] foundRows = dt.Select("RequestID = '" + yourValueToSearch + "'");

最终你也可以使用Linq

var foundRows = dt.AsEnumerable()
                  .Where(x => x.Field<int>("RequestID") == yourValueToSearch)
                  .ToArray()
相关问题