在C#数据库连接中选择一些行

时间:2015-04-01 07:21:44

标签: c# sql database

我使用数据库连接来连接数据库,我选择了数据库表中的一些行,如下代码:

OleDbConnection objConnection = new OleDbConnection("server=localhost;database=sample;Data Source=|DataDirectory|\\sample.accdb");

objDataAdapter = new OleDbDataAdapter("SELECT description, category, account, price FROM SampleTable WHERE Select_ID = 12", objConnection);

现在这段代码从SampleTable中选择16行,其中Select_ID为12,之后我需要行3,5,7如何选择这行?

4 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER功能。如果您在查询中使用它,您将按ROW_NUMBER选择所有行。如果我读得正确,你需要结果集的3,5,7行,所以你必须使用子查询:

SELECT * FROM (
    SELECT description, category, account, price FROM SampleTable WHERE Select_ID = 12
) WHERE ROW_NUMBER() IN (3,5,7)

在内部查询中,您将获得16行结果。外部查询现在将该结果用作表/数据源,并选择所需的行。

答案 1 :(得分:0)

DataTable dt = new DataTable(); // get your data into this datatable

        DataRow[] dr;
        dr = dt.Select("WHERE Select_ID = 12");
        if (dr.Length > 0)
        {
            //do something
        }

答案 2 :(得分:0)

如果按列排序" id",则

SELECT t.description, t.category, t.account, t.price FROM (
 SELECT ROW_NUMBER() OVER (ORDER BY id) as RowN, description, category, account, price FROM SampleTable WHERE Select_ID = 12
) as t WHERE RowN in (3,5,7)

else(ORDER BY id)更改为您的列

答案 3 :(得分:0)

如果您的DataTable已包含这16行,但您只想要行3,5,7:

int[] indexes = { 2, 4, 6 };
dataTable1 = dataTable1.AsEnumerable()
    .Where((row, index) => indexes.Contains(index))
    .CopyToDataTable();

如果您使用支持排名功能的数据库,则可以使用ROW_NUMBER。如果您使用SQL-Server> = 2005,则可以使用:

string sql = @"
WITH CTE AS
(
    SELECT description, category, account, price,
           rn = ROW_NUMBER() OVER (ORDER BY Select_ID, description, category, account, price)
    FROM SampleTable 
    WHERE Select_ID = 12
)
SELECT description, category, account, price
FROM CTE
WHERE rn IN ( 3, 5, 7 );"