4

我有 5 个随机的男性和女性名字。我需要根据性别插入随机名称。但是我们如何从 SQL 中的一组 5 个名称中随机插入名称。可能吗?

4

7 回答 7

10
select name from table order by newid()
于 2013-07-02T17:15:58.923 回答
5

使用名称和整数 ID 创建一个表。然后使用带有 % 5 的 RAND() 降低到 0 到 4 之间的值(含)。如果您想要男性,请添加 1,如果您想要女性,请添加 6。像这样:

Create table RandomNames
(id int,
 name varchar(100),
 gender char(1)
)

insert into RandomNames
(id, name,gender)
select 1,'Bill','M'
union
select 2,'John','M'
union
select 3,'Steve','M'
union
select 4,'Mike','M'
union
select 5,'Phil','M'
union
select 6,'Sarah','F'
union
select 7,'Ann','F'
union
select 8,'Marie','F'
union
select 9,'Liz','F'
union
select 10,'Stephanie','F'

declare @wantedGender char(1)

select @wantedGender = 'M'

select name 
from RandomNames
where id =  (CAST(RAND()*100 as int) % 5) + case when @wantedGender = 'M' then 1 else 6 end 
于 2013-07-02T17:18:28.780 回答
1

创建一个函数

CREATE FUNCTION [dbo].[getRandomName](@gen varchar(10))
RETURNS @name varchar(50)

AS
BEGIN

   SELECT TOP 1 @name = name FROM table WHERE gender=@gen ORDER BY newid()
END

然后,只需将@gen 传递给这样的函数

select dbo.getRandomName('male')

或者,像这样更新许多行:

UPDATE myNewTable 
   SET newName=dbo.getRandomName('male')
WHERE gender='male'
于 2013-08-23T18:46:50.020 回答
1

在 SQL Server 中,获得“随机”的最佳方法是使用newid(). 您可以按此排序以获得排序列表。

如果每个性别有五个名称,则可以使用 CTE 来存储它们。然后插入看起来像:

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();
于 2013-08-23T20:56:00.390 回答
1

目前正在解决这个问题。Rand() 不起作用,您将获得所有 300 行的相同随机数。NewID() 不会给你一个可用的值。但是,您可以将以下公式用于每行 1 到 5 之间的随机值。NewID 和 Checksum 每次都会给你一个随机数,但其中包括负数,然后除以 4 并取余数(0-4),然后取该数字的绝对值并将其加 1。然后使用该随机数从名称表中选择一个值。

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

在命令中使用它:

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
于 2013-08-23T16:36:20.203 回答
1

Store the 5 random names for male in one table and the 5 random names for female in another table. Select a random integer between 1 and 5 and cross reference to male or female table using an inner join.

于 2013-07-02T17:14:12.853 回答
0
select top 1 name from RandomNames 
where gender = 'M' order by newid()

样品小提琴

于 2013-08-24T07:38:51.757 回答