[英]Function to select random Id
我想選擇一個隨機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."
我究竟做錯了什么?
使用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。
你可以使用newid()
檢查它,它將創建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;
我提供了這個答案,我從這篇文章中改編了......
-- 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 |
+--------+-------------+-----------------+
通過此鏈接輕松生成ASCII表。 希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.