SQL Server 2012 Random string from a list

前端 未结 5 666
暖寄归人
暖寄归人 2021-01-01 18:20

say I have 3 values, Bill, Steve, Jack. and I want to randomly update a table with those values, eg

Update contacts set firstname = (\'Bill\',\'Steve\',\'Jack\') whe

5条回答
  •  清歌不尽
    2021-01-01 18:53

    This is addition answer using Ben Thul answer:

    DECLARE @index INT
    SELECT  @index = CAST(RAND() * 3 + 1 AS INT)
    UPDATE contacts SET firstname = CHOOSE(@index,'Bill','Steve','Jack') WHERE city = 'NY'
    

    Using RAND function will random values from 1 to 3. Then, based on resulted int value the CHOOSE function will pick values depending on the order/index of the given strings. In which 'Bill' is the index 1 then so on.

    You can test the random int values by using below SQL script:

    SELECT CAST(RAND() * 3 + 1 AS INT)
    

    I have a weird issue if use the RAND directly to the query for example below:

    SELECT CHOOSE( CAST(RAND() * 3 + 1 AS INT),'Bill','Steve','Jack')
    

    There are instance that value is NULL.

提交回复
热议问题