vendredi 3 décembre 2021

Generate random numbers, letters or characters within a range

I'm in the middle of a data anonymization for SQL Server.

I have this 3 formulas that help me create what I want:

SELECT CHAR(cast((90 - 65) * rand() + 65 AS INTEGER)) -- only letters
SELECT CAST((128 - 48) * RAND() + 48 AS INTEGER) -- only numbers
SELECT CHAR(CAST((128 - 48) * RAND() + 48 AS INTEGER)) -- letters, numbers, symbols

However, this only can create 1 number or 1 letter or 1 symbol.

I want to have the freedom that allows me to create a random string or number of the length I want. Like 3 or 5 numbers, 3 or 5 letters, 3 or 5 between numbers, letters or symbols.

I also have found something very close to what I want:

SELECT LEFT(CAST(NEWID() AS VARCHAR(100)), 3) -- letters and numbers 

this is a very smart idea because uses NEWID() and it allows me to create a random sequence of numbers and letters of the length I want (3 in this case). But symbols are missing.

I need 3 different SELECT:

  • One for numbers only
  • One for letters only
  • One for numbers, letters and symbols

With the freedom of choice about the length of the data.




Aucun commentaire:

Enregistrer un commentaire