• Mike C (6/9/2009)


    Someguy (6/9/2009)


    OK. I'll be the one to ask the dumb question:

    Most languages have a random function that does not require you to add seeds and/or do other things to make them work. In C# for example, you can choose to add a seed, but the default doesn't require one.

    So, why does T-SQL default to requiring a seed, seeing as doing so creates 'scratch head' situations like this? It sure seems like we're doing some big back flips here to achieve something that's pretty common in programming tasks. We're using functions like 'NewID' to give us the random number that Random can't do without.

    And technically, the guid generated by NewID is not totally random. For practical matters like this excercise, sure. But Random and Unique aren't necesarily the same things. But I digress...

    In T-SQL you can use RAND() without a seed. If you want better random numbers check out one of my favorite random number generators with very nice statistical properties: Mersenne Twister at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html. Most of the time in SQL though, the NEWID() function is "good enough" since we are usually just talking about quick and practical methods of sampling data in a non-orderly fashion.

    BTW, the "backflips" are a result of two factors: (1) the definition of the RAND() function, which generates one value per invocation, and (2) the fact that SQL is a declarative language. NEWID() guarantees a different value for every row of a result set, RAND() does not provide that; hence the issue the author is trying to get around.

    RAND() in T-SQL works exactly the same way as RAND() in any computer language.... one row or value at a time.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)