sql server - Update a table column with shuffled numbers within a range -


i want update table column -code- shuffled numbers within range, no duplicates , without missing number range. example range 1-9 , following table:

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   

i want result in above example. using sql server 2008.

try this:

declare @t table ( id int, code int )  insert  @t         ( id ) values  ( 1 ),         ( 2 ),         ( 3 ),         ( 4 ),         ( 5 ),         ( 6 ),         ( 7 ),         ( 8 ),         ( 9 );    cte           ( select   * ,                         row_number() on ( order newid() ) rn                    @t              )     update  cte     set     code = rn   select  *    @t 

output:

id  code 1   2 2   7 3   4 4   1 5   6 6   8 7   5 8   9 9   3 

if want manually set range can set starting number of range , like:

declare @start int = 101  declare @t table ( id int, code int )  insert  @t         ( id ) values  ( 1 ),         ( 2 ),         ( 3 ),         ( 4 ),         ( 5 ),         ( 6 ),         ( 7 ),         ( 8 ),         ( 9 );     cte           ( select   * ,                         row_number() on ( order newid() ) rn                    @t              )     update  cte     set     code = rn + @start - 1   select  *    @t     

output:

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

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -