views:

33

answers:

2

Hello

What is the best way to sort records on Guid. Below never gives right results.

    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

Instead using Guid, how can i generate Sequential Integers in my select.

Thanks

A: 

Your question is not that clear. Do you want the GUIDs to sort in lexicographic order? If so you can cast them to char(36). For the bit about generating sequential integers do you need ROW_NUMBER()?

SELECT 
      ID, 
      UID, 
      ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS rn
FROM UIDs ORDER BY  CAST(UID AS CHAR(36)), ID
Martin Smith
+1  A: 

Don't is the best answer.

This explains how SQL Server: How are GUIDs sorted by SQL Server?

You have NEWSEQUENTIALID but this is not guaranteed to sort as you expect. And why use a GUID whan you have ranking fucntions?

gbn
+1 amen, brother!
marc_s