选择随机编号的功能

时间:2018-12-22 13:23:18

标签: sql sql-server

我想选择一个随机ID,其中我的列Guy_Checked不是1。

这是我的代码:

CREATE FUNCTION dbo.get_rand_id()  
RETURNS int   
AS   
BEGIN  
    DECLARE @ret int;  
    set @ret = (select top 1 Guy_ID
    FROM SantaGuys
    WHERE Guy_Checked <> 1
    ORDER BY RAND())
RETURN @ret;  
END; 

SQL Server返回错误443,类似...

"Invalid use of the "rand" operator, which has side effects, in a function." 

我在做什么错了?

3 个答案:

答案 0 :(得分:2)

改为使用NEWID()

CREATE FUNCTION dbo.get_rand_id()  
RETURNS int   
AS   
BEGIN  
    DECLARE @ret int;  
    SET @ret = (SELECT top 1 Guy_ID
                FROM SantaGuys
                WHERE Guy_Checked <> 1
                ORDER BY NEWID()
               )
    RETURN @ret;  
END; 

RAND()实际上是整个查询过程中的常量-在查询开始处理之前对其进行一次评估。每次NEWID()都会生成一个不同的ID。

答案 1 :(得分:1)

您可以使用newid() check this,它将创建一个类型为uniqueidentifier的唯一值。

CREATE FUNCTION dbo.get_rand_id()  
RETURNS int   
AS   
BEGIN  
    DECLARE @ret int;  
    set @ret = (select top 1 Guy_ID
    FROM SantaGuys
    WHERE Guy_Checked <> 1
    ORDER BY NEWID())
RETURN @ret;  
END; 

答案 2 :(得分:0)

我提供的答案是我根据this post ...

改编而成的
-- Build the table
SELECT 123 as Guy_ID
      ,0 as Guy_Checked INTO SantaGuys;

INSERT INTO SantaGuys VALUES (234, 1);
INSERT INTO SantaGuys VALUES (456, 0);
INSERT INTO SantaGuys VALUES (567, 1);

GO


-- Create a view of RAND() to work around the Invalid use of side-effecting error
CREATE VIEW v_get_rand_id
AS
SELECT RAND() as rand_id;
GO


-- Build the function with parameters that will be in your SELECT query
CREATE FUNCTION dbo.get_rand_id(@my_Guy_ID as int, @my_Guy_Checked as int)  
RETURNS float    
AS   
BEGIN  
 DECLARE @my_rand_id float; 

 SET @my_rand_id = (SELECT CASE WHEN @my_Guy_Checked <> 1 
                                THEN v.rand_id 
                                ELSE 0 END as my_rand_id 
                      FROM v_get_rand_id v)

 RETURN @my_rand_id;  

END; 

GO

-- Run your query and enjoy the results
SELECT sg.Guy_ID
      ,sg.Guy_Checked
      ,dbo.get_rand_id(sg.Guy_ID, sg.Guy_Checked) as my_rand_id
  FROM SantaGuys sg;

这是一个结果...

+--------+-------------+-----------------+
| Guy_ID | Guy_Checked |   my_rand_id    |
+--------+-------------+-----------------+
|    123 |           0 | 0.5537264103585 |
|    234 |           1 |               0 |
|    456 |           0 |  0.227823559345 |
|    567 |           1 |               0 |
+--------+-------------+-----------------+

轻松地从this link生成ASCII表。希望这会有所帮助