使用范围内的随机数更新表列

时间:2015-04-29 06:25:09

标签: sql-server sql-server-2008

我想更新一个表格列 - Code - 在其范围内使用随机数字,没有重复项且没有错过该范围内的数字。 例如,范围是1-9,以下是表格:

Id|Name|Code

1 | AC | 2  
2 | AB | 1  
3 | CB | 5  
4 | DE | 9  
5 | FE | 3  
6 | AE | 4  
7 | FD | 6  
8 | BD | 7  
9 | DC | 8  

我想在上面的例子中得到结果。我正在使用SQL Server 2008

2 个答案:

答案 0 :(得分:4)

试试这个:

DECLARE @t TABLE ( ID INT, Code INT )

INSERT  INTO @t
        ( ID )
VALUES  ( 1 ),
        ( 2 ),
        ( 3 ),
        ( 4 ),
        ( 5 ),
        ( 6 ),
        ( 7 ),
        ( 8 ),
        ( 9 );
WITH    cte
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( ORDER BY NEWID() ) AS rn
               FROM     @t
             )
    UPDATE  cte
    SET     code = rn


SELECT  *
FROM    @t

输出:

ID  Code
1   2
2   7
3   4
4   1
5   6
6   8
7   5
8   9
9   3

如果您想手动设置范围,则可以设置范围的起始编号,并执行以下操作:

DECLARE @start INT = 101

DECLARE @t TABLE ( ID INT, Code INT )

INSERT  INTO @t
        ( ID )
VALUES  ( 1 ),
        ( 2 ),
        ( 3 ),
        ( 4 ),
        ( 5 ),
        ( 6 ),
        ( 7 ),
        ( 8 ),
        ( 9 );

WITH    cte
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( ORDER BY NEWID() ) AS rn
               FROM     @t
             )
    UPDATE  cte
    SET     code = rn + @start - 1


SELECT  *
FROM    @t    

输出:

ID  Code
1   104
2   108
3   107
4   105
5   102
6   103
7   106
8   101
9   109

答案 1 :(得分:0)

  • $scope.AddSelected = function () { var selected = $scope.selection console.log(selected); } $scope.selection = []; $scope.toggleSelection = function toggleSelection(movie) { var idx = $scope.selection.indexOf(movie); if (idx > -1) { $scope.selection.splice(idx, 1); } else { $scope.selection.push(movie); } }; 会为我们提供一种随机ID,您可以将其用于随机播放
  • 正如Giorgu Nakeuri回答的那样,您可以使用NEWID()进行一系列连续播放,并始终从ROW_NUMBER()
  • 开始

所以我建议你使用这样的查询来改组一个不同的起始点1的非连续范围:

1

示例结果是:

;With t as (    
    SELECT *, ROW_NUMBER() OVER (ORDER BY NEWID()) As rndrn
    FROM (
        SELECT *, ROW_NUMBER() OVER (ORDER BY Id) As rn 
        FROM yourTable ) t1)
SELECT Id, Name, (SELECT ti.Id FROM t ti WHERE ti.rn = t.rndrn) As Code
FROM t
ORDER BY Id