Números aleatorios y generación de datos con T-SQL


<< Función POWER T-SQL/ Function "POWER" in T-SQL

Esto no es nuevo (aunque para mí sí resultó así), pero es bastante útil tenerlo a mano para cuando se requiera.

En proyectos de bases de datos he requerido llenar algunas tablas con datos ficticios para probar diferentes operaciones, tanto de BD como de aplicación. Así fue que conocí la efectividad de combinar algunas funciones:

  • NEWID() genera un nuevo identificador GUID formado por 32 caracteres hexadecimales
  • CHECKSUM() hace la conversión a un entero
  • ABS() obtiene el valor absoluto de un número

CHECKSUM(NEWID()) genera un número entero aleatorio (positivo o negativo)
ABS(CHECKSUM(NEWID())) genera un número entero aleatorio positivo
ABS(CHECKSUM(NEWID())) % N genera un número entero aleatorio entre 0 y N-1 porque % como operador aritmético calcula el residuo de la división entera

Si queremos generar una fecha aleatoria durante el 2017 podemos usar


(ABS(CHECKSUM(NEWID())) % 11) + 1 para el mes
(ABS(CHECKSUM(NEWID())) % 27) + 1 para el día

Uniendo y usando CAST para concatenar quedaría


CAST((ABS(CHECKSUM(NEWID())) % 11) + 1 as varchar(2)) + '-' + CAST((ABS(CHECKSUM(NEWID()))%27)+1 as varchar(2)) + '-2017'

Pero queda, en ocasiones como 8-3-2017 en vez de 08-03-2017


Eso se corrige con RIGHT() que recupera la parte derecha de una cadena. Quedando como ...


RIGHT('0' + CAST((ABS(CHECKSUM(NEWID()))%11)+1 as varchar(2)) , 2) + '-' +
RIGHT('0' + CAST((ABS(CHECKSUM(NEWID()))%27)+1 as varchar(2)) , 2) + '-2017'



This isn't new (although for me it did) but it's very useful to have it handy for when it will required.

In database projects, I have required to fill som tables with fake data for test different operations, both of database and application. So it was that I met the effectiveness of combining some functions:

  • NEWID() generates a new GUID ID formed by 32 hexadecimal characters
  • CHECKSUM() does a conversion to an integer
  • ABS() gets the abs value of an integer

CHECKSUM(NEWID()) generates a random integer number (possitive or negative).
ABS(CHECKSUM(NEWID())) generates a random possitive integer number.
ABS(CHECKSUM(NEWID())) % N generates a random integer number between zero and n-1 because the % arithmetic operator calculates the modulus of an integer division.

If we want to generate a random date during 2017, we can use


(ABS(CHECKSUM(NEWID())) % 11) + 1 for the month
(ABS(CHECKSUM(NEWID())) % 27) + 1 for the day (27 to avoid dates out of range, like february 30th)

Joining and using the CAST function to concatenate would be


CAST((ABS(CHECKSUM(NEWID())) % 11) + 1 as varchar(2)) + '-' + CAST((ABS(CHECKSUM(NEWID()))%27)+1 as varchar(2)) + '-2017'

But it results, some times, like 8-3-2017 instead of 08-03-2017


It can be corrected with RIGHT() that returns the right part of a string. Staying as ...


RIGHT('0' + CAST((ABS(CHECKSUM(NEWID()))%11)+1 as varchar(2)) , 2) + '-' +
RIGHT('0' + CAST((ABS(CHECKSUM(NEWID()))%27)+1 as varchar(2)) , 2) + '-2017'

Comentarios

Entradas populares