-1

我想对 MS SQL 中的列进行排序。我有一个表说 Performance 如下所示,我的要求是对其进行排序,这可以通过“列名”使用 order 轻松完成,但是如何以排序方式永久保存它,我的意思是我不只是想要使用 select 语句查看排序的数据实际上我想对此视图进行永久更改。

Marks    Roll number    Name   
44         5            Mike
22         2            Robin
44         1            Jack
34         3            a
22         4            b

预期的:

22      2          Robin
22      4          b
34      3          a
44      1          Jack
44      5          Mike
4

1 回答 1

4

You can't. Relational databases have no concept of ordering the rows in a table. If you want ordered output, you must use an ORDER BY clause. This is a fundamental fact and is not something you can work around.

In SQL Server 2000, in (essentially) error, Microsoft allowed views to have an ORDER BY clause, which did order the output. However, in SQL Server 2005 this was changed because it was never really right to operate that way.

You could try the SELECT TOP (2147483647) * FROM dbo.Blah B ORDER BY B.Col; trick, but that won't cut it in later versions of SQL Server, either. The ordering behavior of TOP is a side effect, not a main effect, and shouldn't be relied on in a view. Do it right and put sorting where it should be: in the presentation layer or in the final, outer query that is submitted to the database (ala SELECT Columns FROM dbo.View ORDER BY X;).

A little more on not ordering rows in a table: yes, there are clustered indexes, but you can't rely on the data returning ordered for several reasons:

  • A nonclustered index may be used to satisfy the query, so the clustered index's ordering will have no impact on the output rowset's ordering.
  • There may be no clustered index at all on the table.
  • While each clustered index page's rows are less than the next page and greater than the previous page, the rows inside each page are not themselves ordered.
  • Parallelism can change the order that rows are produced as one stream may return faster or slower than others.
  • During query execution, if another process is already reading some of the rows that will satisfy the current query, that data may be borrowed for the current query out of order in order to save reads (after which the current query will fetch only the remaining rows it is missing).

There is one simple, reliable, and required way to get an ordered rowset: ORDER BY.

于 2013-06-08T00:16:42.797 回答