2015-05-12 18 views
9

dire che ho 3 valori, Bill, Steve, Jack. e voglio aggiornare in modo casuale un tavolo con quei valori, ad esempio contattiSQL Server 2012 Stringa casuale da un elenco

Aggiornare Imposta cognome = ('Bill', 'Steve', 'Jack') dove city = 'NY'

come faccio RANDOMIZE questi valori?

Grazie

risposta

13

si può fare questo con il seguente trucco:

update c set name=ca.name 
from contacts c 
outer apply(select top 1 name 
      from (values('bill'),('steve'),('jack')) n(name) 
      where c.id = c.id order by newid())ca; 

c.id = c.id è solo un predicato fittizio che costringe motore SQL per chiamare subquery per ogni riga esterna. Ecco il violino http://sqlfiddle.com/#!6/8ecca/22

+0

Sto provando a farlo diventare una funzione e posta una domanda su http://stackoverflow.com/questions/30332857/function-to-randomly-select- a-value-from-a-list-sql-server-2012 qualsiasi aiuto sarebbe apprezzato. Grazie – Bill

3

si può fare qualcosa di simile

-- Storing the list of strings in a CTE 

WITH PossibleValues AS 
(SELECT 'Bill' AS Name, 
      1 AS Number 
    UNION SELECT 'Steve' AS NAME, 
     2 AS Number 
    UNION SELECT 'Jack' AS NAME, 
     3 AS Number 
) 

UPDATE contacts 
SET firstname = (SELECT Name 
          FROM PossibleValues 
          WHERE PossibleValues.Number = FLOOR(RAND()*(4-1)+1)) 
WHERE City = 'NY' 

Il FLOOR(RAND()*(4-1)+1) sarebbe generare un numero casuale da 1 a 3 ogni volta che si esegue la query. Pertanto, sceglierai un nome casuale ogni volta.

+1

Grazie, continua a ricevere l'ultimo valore (es. Jack) per tutte le righe. c'è un modo per randomizzarlo per diverse file nella stessa esecuzione? – Bill

+0

Provate questo https://stackoverflow.com/a/26188792/2343 – Sameer

7

Ecco un po 'di amore usando choose

with cte as (
    select *, (ABS(CHECKSUM(NewId())) % 3) + 1 as n 
    from contacts 
    where city = 'NY' 
) 
update cte 
set firstname = choose(n, 'Bill','Steve','Jack')