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
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();