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

前端 未结 19 1218
逝去的感伤
逝去的感伤 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:29

    If you need to preserve your seed so that it generates the "same" random data every time, you can do the following:

    1. Create a view that returns select rand()

    if object_id('cr_sample_randView') is not null
    begin
        drop view cr_sample_randView
    end
    go
    
    create view cr_sample_randView
    as
    select rand() as random_number
    go
    

    2. Create a UDF that selects the value from the view.

    if object_id('cr_sample_fnPerRowRand') is not null
    begin
        drop function cr_sample_fnPerRowRand
    end
    go
    
    create function cr_sample_fnPerRowRand()
    returns float
    as
    begin
        declare @returnValue float
        select @returnValue = random_number from cr_sample_randView
        return @returnValue
    end
    go
    

    3. Before selecting your data, seed the rand() function, and then use the UDF in your select statement.

    select rand(200);   -- see the rand() function
    with cte(id) as
    (select row_number() over(order by object_id) from sys.all_objects)
    select 
        id,
        dbo.cr_sample_fnPerRowRand()
    from cte
    where id <= 1000    -- limit the results to 1000 random numbers
    

提交回复
热议问题