我需要为员工列表分配1到1000之间的唯一编号(或者有多少员工)。这些数字不能重复,需要按照随机顺序对照员工列表。这些数字也需要每周重新生成,以便为员工分配一个新号码。
我尝试使用以下内容,但脚本速度很慢,并为所有员工返回相同的编号。
DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT
SET @Lower = 1
SET @Upper = 1000
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
select personnum, firstnm, lastnm, (SELECT @Random)
from person
任何人都可以解释如何做到这一点? 谢谢
答案 0 :(得分:4)
适用于mssql server 2005 +
select personnum, firstnm, lastnm, row_number() over (order by newid()) randomnumber
from person
答案 1 :(得分:0)
为它创建一个函数。这是我们使用的一个:
ALTER FUNCTION [dbo].[fn_GenerateUniqueNumber]()
RETURNS char(10)
AS
BEGIN
--DECLARE VARIABLES
DECLARE @RandomNumber VARCHAR(10)
DECLARE @I SMALLINT
DECLARE @RandNumber FLOAT
DECLARE @Position TINYINT
DECLARE @ExtractedCharacter VARCHAR(1)
DECLARE @ValidCharacters VARCHAR(255)
DECLARE @VCLength INT
DECLARE @Length INT
--SET VARIABLES VALUE
SET @ValidCharacters = '0123456789'
SET @VCLength = LEN(@ValidCharacters)
SET @ExtractedCharacter = ''
SET @RandNumber = 0
SET @Position = 0
SET @RandomNumber = ''
SET @Length = 10
SET @I = 1
WHILE @I < ( @Length + 1 )
BEGIN
SET @RandNumber = (SELECT RandNumber FROM [RandNumberView])
SET @Position = CONVERT(TINYINT, ( ( @VCLength - 1 ) * @RandNumber + 1 ))
SELECT @ExtractedCharacter = SUBSTRING(@ValidCharacters, @Position, 1)
SET @I = @I + 1
SET @RandomNumber = @RandomNumber + @ExtractedCharacter
END
RETURN @RandomNumber
END
要使用它,请执行以下操作:
SELECT personnum, firstnm, lastnm,dbo.fn_GenerateUniqueNumber()
FROM person
您可以修改参数和允许值,以确保它是您想要的数字类型。