How to insert random characters into sql database column?

I want to fill a column of my database table with 253 rows "M" and "F" accidentally placed in the column, is this possible?

An example of how this might look:

Gender: M M F M F F M F M 
+5
source share
3 answers

For MS SQL you can use NEWID and CHECKSUM :

  UPDATE Users SET Gender = (CASE WHEN ABS(CHECKSUM(NEWID()) % 2) = 1 THEN 'M' ELSE 'F' END) 
  • NEWID () generates a random GUID

  • CHECKSUM () generates a hash of this GUID

  • ABS () to do this is either 1 or 0


ATTENTION! Although some people suggest using the RAND - function , do not use it for this particular case. The request is as follows:

 UPDATE Users SET Gender = CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END 

.. will cause you to have all the values โ€‹โ€‹of either M or F.

You can potentially use a RAND function with some value, for example Id, but the distribution of values โ€‹โ€‹will not be very good: for example, the first 30 -40% of all M, then 30-40% of all F, then M again.

+3
source

You can use the RAND () function.

Please read the following URL: [enter link here] [1]

https://docs.microsoft.com/en-us/sql/t-sql/functions/rand-transact-sql

+1
source

Try this to reduce the โ€œ0.5โ€ to improve the odds of choosing if you want the โ€œMโ€ to be more dominant.

  SELECT CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END 
0
source

Source: https://habr.com/ru/post/1269522/


All Articles