For SQL select returning more than 1 value, how are they sorted when Id is GUID?

巧了我就是萌 提交于 2019-12-24 05:32:23

问题


I'm wondering how SQL Server orders data that is returned from a query and the Id columns of the respective tables are all of type uniqueidentifier.

I'm using NHibernate GuidComb when creating all of the GUIDs and do things like:

Sheet sheet = sheetRepository.Get(_SheetGuid_); // has many lines items
IList<SheetLineItem> lineItems = sheet.LineItems;

I'm just trying to figure out how they'll be ordered when I do something like:

foreach (SheetLineItem lineItem in lineItems)

I can't see to find a good article on the way GUIDs are compared by SQL when being ordered, if that's what's happening.


回答1:


Unless you incude an ORDER BY clause SQL Server doesn't guarantee any order on the results. It may sem to come back in the some order consistently (e.g. clustered index order) but you can't be sure this will always be the case (e.g. if the query is split and executed on multiple threads, when the results are combined, the order may be different on each execution since the threads may complete in different orders).

The only way to get a particular order is to use an ORDER BY clause. In NHibernate, this would be achieved by speifying an order-by="..." on your bags (or equivalent) in your mapping files.

See the NHibernate docs for more info on "order-by": http://nhibernate.info/doc/nh/en/index.html




回答2:


GUIDs are sorted this way by the ORDER BY. Quoting the article...

  • 0..3 are evaluated in left to right order and are the less important, then
  • 4..5 are evaluated in left to right order, then
  • 6..7 are evaluated in left to right order, then
  • 8..9 are evaluated in right to left order, then
  • A..F are evaluated in right to left order and are the most important


来源:https://stackoverflow.com/questions/2723774/for-sql-select-returning-more-than-1-value-how-are-they-sorted-when-id-is-guid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!