选择UDF中的随机记录

时间:2015-01-16 08:06:47

标签: sql-server tsql

我正在sql server 2012中编写一个函数。   我开始知道我们不能在sql server中的函数的select语句中使用RAND()NEWID()函数。 我的功能是这样的:

CREATE FUNCTION Keywordsuggester (@userid INT) 
returns @suggestor_tab TABLE ( 
  keywordid       INT, 
  keywordname     VARCHAR(max), 
  keywordcategory VARCHAR(max)) 
AS 
  BEGIN 
      DECLARE @category_table TABLE 
        ( 
           category_name VARCHAR(max), 
           category_id   INT, 
           rownum        INT 
        ) 
      DECLARE @ID INT = 1 
      DECLARE @COUNT INT = 0 
      DECLARE @I INT = 1 

      INSERT INTO @category_table 
      SELECT kc.NAME, 
             kc.id, 
             k.NAME, 
             d.NAME, 
             Row_number() 
               OVER( 
                 ORDER BY d.id ASC) AS rownum 
      FROM   dtypes d 
             JOIN keywords k 
               ON d.NAME LIKE '%' + k.NAME + '%' 
             JOIN keywordscategory kc 
               ON k.categoryid = kc.id 
      WHERE  d.userid = @userid 

      SELECT @count = rownum 
      FROM   @category_table 

      WHILE @count > @I 
        BEGIN 
            INSERT INTO @suggestor_tab 
            SELECT TOP 5 kc.id, 
                         k.NAME, 
                         kc.NAME 
            FROM   kwords k 
                   JOIN @category_table ct 
                     ON k.categoryid = ct.category_id 
                   JOIN kwcategory kc 
                     ON kc.NAME = ct.category_name 
            WHERE  ct.rownum = @I 

            --Here I'm inserting top 5 records for each category into the suggestor_tab,instead I have to insert random 5 records for each category(i.e.,@I)
            SET @I=@I + 1 
        --return 
        END 

      INSERT INTO @suggestor_tab 
      SELECT kc.id, 
             k.NAME, 
             kc.NAME 
      FROM   kwords k 
             JOIN @category_table ct 
               ON k.categoryid = ct.category_id 
             JOIN kwcategory kc 
               ON kc.NAME = category_name 

      RETURN 
  END 

如何获得每个类别的随机记录(即,while循环中的@I)。 我尝试过这样的查询:

    SELECT TOP 5 k.NAME 
FROM   kwords k 
       JOIN @category_table ct 
         ON k.category_id = ct.id 
       JOIN kwcategory kc 
         ON kc.NAME = category_name 
WHERE  ct.rownum = @I 
ORDER  BY Newid() 

会抛出如下错误:

Invalid use of a side-effecting operator 'newid' within a function.

有没有这样做? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您无法在Non-deterministic中使用UDF个功能。

创建View并在order by

中使用它
create view Random 
as
select newid() as New_id

更改select这样的内容。

SELECT TOP 5 k.NAME
FROM   KWords k
        JOIN @category_table ct
            ON k.category_id = ct.id
        JOIN kwcategory kc
            ON kc.NAME = category_name
WHERE  ct.rownum = @I
ORDER  BY (SELECT new_id
            FROM   random)