How do I generate random number for each row in a TSQL Select?

前端 未结 19 1219
逝去的感伤
逝去的感伤 2020-11-22 07:03

I need a different random number for each row in my table. The following seemingly obvious code uses the same random value for each row.

SELECT table_name,          


        
19条回答
  •  没有蜡笔的小新
    2020-11-22 07:37

    When called multiple times in a single batch, rand() returns the same number.

    I'd suggest using convert(varbinary,newid()) as the seed argument:

    SELECT table_name, 1.0 + floor(14 * RAND(convert(varbinary, newid()))) magic_number 
    FROM information_schema.tables
    

    newid() is guaranteed to return a different value each time it's called, even within the same batch, so using it as a seed will prompt rand() to give a different value each time.

    Edited to get a random whole number from 1 to 14.

提交回复
热议问题