在GUID SQL Server 2008上排序

时间:2010-09-06 23:04:04

标签: sql-server sql-server-2008

在Guid上对记录进行排序的最佳方法是什么?以下从未给出正确的结果。

    With UIDs As (--                        
            Select ID =  1, UID = NEWID() 
    Union   Select ID =  2, UID = NEWID()
    Union   Select ID =  3, UID = NEWID()
    Union   Select ID =  4, UID = NEWID()
    Union   Select ID =  5, UID = NEWID()
    Union   Select ID =  6, UID = NEWID()
    Union   Select ID =  7, UID = NEWID()
    Union   Select ID =  8, UID = NEWID()
    Union   Select ID =  9, UID = NEWID()
    Union   Select ID = 10, UID = NEWID()
    Union   Select ID = 11, UID = NEWID()
    Union   Select ID = 12, UID = NEWID()
    Union   Select ID = 13, UID = NEWID()
    Union   Select ID = 14, UID = NEWID()
    Union   Select ID = 15, UID = NEWID()
    Union   Select ID = 16, UID = NEWID()
)
Select * From UIDs Order BY  UID, ID

相反使用Guid,如何在我的选择中生成顺序整数。

由于

2 个答案:

答案 0 :(得分:17)

SELECT * 
FROM myTable 
ORDER BY CAST(myGuid AS VARCHAR(36))

答案 1 :(得分:4)

不是最好的答案。

这解释了SQL Server:How are GUIDs sorted by SQL Server?

的方式

您有NEWSEQUENTIALID,但这是not guaranteed按您的预期排序。为什么在有排名功能时使用GUID?