2

I would like to update existing records in an oracle table with a random string (YYYY-DD)
I have successfully created a query that returns a random date value like so:

select  to_char(TO_DATE('2003/07/09', 'yyyy/mm/dd') + trunc(dbms_random.value(0,(TO_DATE('2003/07/09', 'yyyy/mm/dd')-TO_DATE('2018/07/09', 'yyyy/mm/dd')+1))),
                         'YYYY-MM') rDate   from dual

But for some reason my update script is setting the same value to all the records why is it not random?

CREATE TABLE tmp_del_me (    
    name varchar(255),
    year_month_started varchar(255)
);

insert into tmp_del_me (name)VALUES ('a');
insert into tmp_del_me (name)VALUES ('b');
insert into tmp_del_me (name)VALUES ('c');
insert into tmp_del_me (name)VALUES ('d');


UPDATE tmp_del_me
SET  year_month_started = (
                    select  to_char(TO_DATE('2003/07/09', 'yyyy/mm/dd') + trunc(dbms_random.value(0,(TO_DATE('2003/07/09', 'yyyy/mm/dd')-TO_DATE('2018/07/09', 'yyyy/mm/dd')+1))),
                     'YYYY-MM') rDate   from dual
                     )
            /

drop table tmp_del_me;

1 Answer 1

3

Good Catch!!

Your inner query executes only once and always same value is assigned to year_month_started column.

If you don't use subquery, then the DML works as expected.

UPDATE T1
SET COL1 = 
  to_char(TO_DATE('2003/07/09', 'yyyy/mm/dd') + 
     trunc(dbms_random.value(0,(TO_DATE('2003/07/09', 'yyyy/mm/dd')-
     TO_DATE('2018/07/09', 'yyyy/mm/dd')+1))), 'YYYY-MM') ;

Here is the fiddler link: http://sqlfiddle.com/#!4/43bb3f

Sign up to request clarification or add additional context in comments.

1 Comment

working great, I still don't understand what is the difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.