Generate random names in sql

前端 未结 7 1000
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 16:42

I have 5 random names each for male and female. I need to insert random names based on the gender. But how can we insert names in random from a set of 5 names in SQL. Is it

7条回答
  •  礼貌的吻别
    2021-01-06 17:02

    Working on this problem currently. Rand() wont work, you'll get the same Random number for all 300 rows. NewID() wont give you a value that is usable. You can however use the following formula for a random value between 1 and 5 on every line. NewID and Checksum given you a random number every time, but that includes negative numbers,then you divide by 4 and take the remainder (0-4) so you then take the absolute value of that number and add 1 to it. Then use that random number to select a value from the tables of names.

    ABS(Checksum(NewID()) % 4) + 1
    

    Using it in a command:

    Create table randomnames (ID int identity, name)
    insert into randomnames (name)
    Values ('Tom', 'Dick', 'Harry', 'Jughead', 'Archie'
              ,'Sally','Sue','Peggy', 'Betty', 'Veronica')
    
    update sometablename
    set Name = case gender
        when 'M' then (select name from randomnames where ID = ABS(Checksum(NewID()) % 4)) + 1
        when 'F' then (select name from randomnames where ID = ABS(Checksum(NewID()) % 4)) + 6
    end
    

提交回复
热议问题