Update n random rows in SQL

前端 未结 3 1968
予麋鹿
予麋鹿 2021-02-06 11:00

I have table which is having about 1000 rows.I have to update a column(\"X\") in the table to \'Y\' for n ramdom rows. For this i can have following query

update         


        
3条回答
  •  攒了一身酷
    2021-02-06 12:03

    The following solution works just fine. It's performant and seems to be similar to sample():

    create table t1 as 
        select level id, cast ('item'||level as varchar2(32)) item 
        from dual connect by level<=100000; 
    
    Table T1 created.
    
    update t1 set item='*'||item 
    where exists (
        select rnd from (
            select dbms_random.value() rnd
            from t1
        ) t2 where t2.rowid = t1.rowid and rnd < 0.15
    );
    
    14,858 rows updated.
    
    Elapsed: 00:00:00.717 
    

    Consider that alias rnd must be included in select clause. Otherwise changes the omptimizer the filter predicat from RND<0.1 to DBMS_RANDOM.VALUE()<0.1. In that case dbms_random.value will be executed only once.

    As mentioned in answer @JonHeller, the best solution remains the pl/sql code block because it allows to avoid full table scan. Here is my suggestion:

    create or replace type rowidListType is table of varchar(18);  
    /
    create or replace procedure updateRandomly (prefix varchar2 := '*') is
        rowidList rowidListType;  
    begin  
        select rowidtochar (rowid) bulk collect into rowidList
        from t1 sample(15)
        ;
        update t1 set item=prefix||item 
        where exists (
            select 1 from table (rowidList) t2
            where chartorowid(t2.column_value) = t1.rowid
        );
        dbms_output.put_line ('updated '||sql%rowcount||' rows.'); 
    end;
    /
    begin  updateRandomly; end;
    / 
    
    Elapsed: 00:00:00.293
    updated 14892 rows.
    

提交回复
热议问题