• Chuck Bevitt - Thursday, July 12, 2018 12:03 PM

    Interesting, because I had thought that any function that took no parameters or a hard coded value parameter would only be evaluated once and would return the same value for every record in the returning record set. Examples of this are Rand() and GetDate(). So it appears that NewID() is an exception. I just had to test this:

    CREATE TABLE dbo.TestFunctions(
     PrimaryKey int IDENTITY(1,1) NOT NULL,
     UniqueID uniqueidentifier NOT NULL,
     Random float NOT NULL,
     CONSTRAINT PK_TestFunctions PRIMARY KEY CLUSTERED (PrimaryKey ASC))

    And then:

    Insert into dbo.TestFunctions (UniqueID, Random)
    Select top 10
     NewID(),
     Rand()
    From Messages

    Where 'Messages' is any table with at least 10 records. Sure enough, UniqueID gets different values while Random gets the same value in every record.

    The fact that Rand() returns the same value for every record has been a source of frustration and innumerable forum threads over the years. As the article illustrates, using NewID() instead of Rand() would solve the problem posted in these forum threads.

    Then you'll be interested in the following articles...
    http://www.sqlservercentral.com/articles/Data+Generation/87901/
    http://www.sqlservercentral.com/articles/Test+Data/88964/

    --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)