Generate random names in sql

前端 未结 7 1049
佛祖请我去吃肉
佛祖请我去吃肉 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:14

    In SQL Server, the best way to get "random" is to use newid(). You can sort by this to get a sorted list.

    If you have five names for each gender, you can use a CTE to store them. The insert would then look like:

    with names as (
          select 'M' as gender, 'Alexander' as name union all
          select 'M', 'Burt' union all
          select 'M', 'Christopher' union all
          select 'M', 'Daniel' union all
          select 'M', 'Eric' union all
          select 'F', 'Alexandra' union all
          select 'F', 'Bertha' union all
          select 'F', 'Christine' union all
          select 'F', 'Daniela' union all
          select 'F', 'Erica'
    )
    insert into table(name)
        select top 1 name
        from names
        where gender = @MyGender
        order by newid();
    

提交回复
热议问题