Comparar valores GUID y uniqueidentifierComparing GUID and uniqueidentifier Values

El tipo de datos de identificador único global (GUID) de SQL Server viene representado por el tipo de datos uniqueidentifier, que almacena un valor binario de 16 bytes.The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. Un GUID es un número binario que sirve principalmente como identificador, el cual que debe ser único en una red formada por varios equipos en muchos sitios.A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites. Los GUID se pueden generar con la llamada a la función NEWID de Transact-SQL, y se tiene la garantía de que son únicos en todo el mundo.GUIDs can be generated by calling the Transact-SQL NEWID function, and is guaranteed to be unique throughout the world. Para obtener más información, vea uniqueidentifier (Transact-SQL).For more information, see uniqueidentifier (Transact-SQL).

Trabajo con valores SqlGuidWorking with SqlGuid Values

Como los valores GUID son largos y poco claros, no resultan significativos para los usuarios.Because GUIDs values are long and obscure, they are not meaningful for users. Si utiliza GUID generados de forma aleatoria en valores de claves e inserta muchas filas, obtendrá E/S aleatoria en los índices, lo que puede afectar al rendimiento negativamente.If randomly generated GUIDs are used for key values and you insert a lot of rows, you get random I/O into your indexes, which can negatively impact performance. Los GUID son también relativamente grandes si se comparan con otros tipos de datos.GUIDs are also relatively large when compared to other data types. En general, se recomienda el uso de GUID solo en situaciones muy limitadas en las que no resulta adecuado ningún otro tipo de datos.In general we recommend using GUIDs only for very narrow scenarios for which no other data type is suitable.

Comparación de valores GUIDComparing GUID Values

Los operadores de comparación se pueden utilizar con valores uniqueidentifier.Comparison operators can be used with uniqueidentifier values. Sin embargo, al comparar los patrones de bits de los dos valores no se implementa el orden.However, ordering is not implemented by comparing the bit patterns of the two values. Las únicas operaciones que se permiten con respecto a un valor de uniqueidentifier son las comparaciones (=, < >, <, >, <=, > =) y la comprobación de NULL (IS NULL y IS NOT NULL).The only operations that are allowed against a uniqueidentifier value are comparisons (=, <>, <, >, <=, >=) and checking for NULL (IS NULL and IS NOT NULL). No se permite ninguna otra operación aritmética.No other arithmetic operators are allowed.

Tanto Guid como SqlGuid tienen un método CompareTo para comparar diferentes valores GUID.Both Guid and SqlGuid have a CompareTo method for comparing different GUID values. Sin embargo, System.Guid.CompareTo y SqlTypes.SqlGuid.CompareTo se implementan de forma distinta.However, System.Guid.CompareTo and SqlTypes.SqlGuid.CompareTo are implemented differently. SqlGuid implementa CompareTo mediante el comportamiento de SQL Server, en el que los últimos seis bytes de un valor son los más significativos.SqlGuid implements CompareTo using SQL Server behavior, in the last six bytes of a value are most significant. Guid evalúa los 16 bytes.Guid evaluates all 16 bytes. En el siguiente ejemplo se muestra esta diferencia conductual.The following example demonstrates this behavioral difference. La primera sección del código muestra valores Guid sin ordenar; la segunda sección muestra los valores Guid ordenados yThe first section of code displays unsorted Guid values, and the second section of code shows the sorted Guid values. la tercera sección muestra los valores SqlGuid ordenados.The third section shows the sorted SqlGuid values. El resultado se muestra debajo del listado de código.The output is displayed beneath the code listing.

private static void WorkWithGuids()
{
    // Create an ArrayList and fill it with Guid values.
    ArrayList guidList = new ArrayList();
    guidList.Add(new Guid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"));
    guidList.Add(new Guid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"));
    guidList.Add(new Guid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE"));

    // Display the unsorted Guid values.
    Console.WriteLine("Unsorted Guids:");
    foreach (Guid guidValue in guidList)
    {
        Console.WriteLine(" {0}", guidValue);
    }
    Console.WriteLine("");

    // Sort the Guids.
    guidList.Sort();

    // Display the sorted Guid values.
    Console.WriteLine("Sorted Guids:");
    foreach (Guid guidSorted in guidList)
    {
        Console.WriteLine(" {0}", guidSorted);
    }
    Console.WriteLine("");
    
    // Create an ArrayList of SqlGuids.
    ArrayList sqlGuidList = new ArrayList();
    sqlGuidList.Add(new SqlGuid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"));
    sqlGuidList.Add(new SqlGuid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"));
    sqlGuidList.Add(new SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE"));

    // Sort the SqlGuids. The unsorted SqlGuids are in the same order
    // as the unsorted Guid values.
    sqlGuidList.Sort();

    // Display the sorted SqlGuids. The sorted SqlGuid values are ordered
    // differently than the Guid values.
    Console.WriteLine("Sorted SqlGuids:");
    foreach (SqlGuid sqlGuidValue in sqlGuidList)
    {
        Console.WriteLine(" {0}", sqlGuidValue);
    }
}
Private Sub WorkWithGuids()

    ' Create an ArrayList and fill it with Guid values.
    Dim guidList As New ArrayList()
    guidList.Add(New Guid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"))
    guidList.Add(New Guid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"))
    guidList.Add(New Guid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE"))

    ' Display the unsorted Guid values.
    Console.WriteLine("Unsorted Guids:")
    For Each guidValue As Guid In guidList
        Console.WriteLine("{0}", guidValue)
    Next
    Console.WriteLine()

    ' Sort the Guids.
    guidList.Sort()

    ' Display the sorted Guid values.

    Console.WriteLine("Sorted Guids:")
    For Each guidSorted As Guid In guidList
        Console.WriteLine("{0}", guidSorted)
    Next
    Console.WriteLine()

    ' Create an ArrayList of SqlGuids.
    Dim sqlGuidList As New ArrayList()
    sqlGuidList.Add(New SqlGuid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"))
    sqlGuidList.Add(New SqlGuid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"))
    sqlGuidList.Add(New SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE"))

    ' Sort the SqlGuids. The unsorted SqlGuids are in the same order
    ' as the unsorted Guid values.
    sqlGuidList.Sort()

    ' Display the sorted SqlGuids. The sorted SqlGuid values are 
    ' ordered differently than the Guid values.
    Console.WriteLine("Sorted SqlGuids:")
    For Each sqlGuidValue As SqlGuid In sqlGuidList
        Console.WriteLine("{0}", sqlGuidValue)
    Next
End Sub

Este ejemplo produce los siguientes resultados.This example produces the following results.

Unsorted Guids:  
3aaaaaaa-bbbb-cccc-dddd-2eeeeeeeeeee  
2aaaaaaa-bbbb-cccc-dddd-1eeeeeeeeeee  
1aaaaaaa-bbbb-cccc-dddd-3eeeeeeeeeee  
  
Sorted Guids:  
1aaaaaaa-bbbb-cccc-dddd-3eeeeeeeeeee  
2aaaaaaa-bbbb-cccc-dddd-1eeeeeeeeeee  
3aaaaaaa-bbbb-cccc-dddd-2eeeeeeeeeee  
  
Sorted SqlGuids:  
2aaaaaaa-bbbb-cccc-dddd-1eeeeeeeeeee  
3aaaaaaa-bbbb-cccc-dddd-2eeeeeeeeeee  
1aaaaaaa-bbbb-cccc-dddd-3eeeeeeeeeee  

Vea tambiénSee also