ExecuteReader以随机顺序返回结果

时间:2015-01-07 17:13:52

标签: c# ado.net

我正在使用DbCommand class中的ExecuteReader命令来执行SQL查询。

SQL查询看起来像这样:

SELECT col_A, col_B, col_C
FROM Table_A

UNION

SELECT col_A, col_B, col_C
FROM Table_B

UNION

SELECT col_A, col_B, col_C
FROM Table_C

当我在SQL Server Management Studio中运行此SQL时,它始终按上述顺序返回结果,即Table_A优先,然后是Table_B等。

但是,当我使用ExecuteReader()方法执行同一个查询时,它会以随机顺序返回结果。

为什么会发生这种情况,我该怎么做才能解决它?

编辑:人们说SQL无法保证订单,但每次我在SQL Server Management Studio中运行查询时,它都按照规定的顺序返回。

3 个答案:

答案 0 :(得分:4)

无法保证此查询的结果将按任何特定顺序排列。如果您希望它们按特定顺序排列,则需要明确订购结果。

您碰巧注意到某些操作结果的排序模式,其结果没有明确的顺序并不代表 维持该模式在所有情况下。

答案 1 :(得分:2)

您可以将查询更改为

SELECT col_A, col_B, col_C, 1 As desiredOrder
FROM Table_A    
UNION    
SELECT col_A, col_B, col_C, 2 As desiredOrder
FROM Table_B    
UNION    
SELECT col_A, col_B, col_C, 3 As desiredOrder
FROM Table_C    
Order By desiredOrder

确保按指定的顺序从每个表中获取行。但是,这并不能保证从每个表返回的行的顺序。

或以下内容以避免返回结果中的额外排序列。

SELECT col_A, col_B, col_C
FROM
    (Select col_A, col_B, col_C, 1 As desiredOrder
    FROM Table_A    
    UNION    
    SELECT col_A, col_B, col_C, 2 As desiredOrder
    FROM Table_B    
    UNION    
    SELECT col_A, col_B, col_C, 3 As desiredOrder
    FROM Table_C) As UnionQuery
Order By desiredOrder

答案 2 :(得分:1)

我解决了这个问题:

Select * from (
SELECT '0' as col_Index, col_A, col_B, col_C
FROM Table_A
UNION
SELECT '1' as col_Index, col_A, col_B, col_C
FROM Table_B
UNION
SELECT '2' as col_Index, col_A, col_B, col_C
FROM Table_C ) Table_Union
Order by col_Index

对不起,如果无法解决您的问题。

感谢。