T-SQL Case statement strange behavior with newid() as randomness source

后端 未结 3 1087
遥遥无期
遥遥无期 2021-01-05 07:59

I\'m using SQL Server 2012.

If I do the following to get a list of random-ish numbers in the range [1,3], it works just fine:

SELECT TOP 100 
    ABS         


        
3条回答
  •  臣服心动
    2021-01-05 08:39

    I cant tell you why, it is indeed strange, but I can give you a workaround. Select the random values into a cte before trying to use them

    ;with rndsrc(value_of_rand) as
    (
    SELECT TOP 100 
        ABS(CHECKSUM(NEWID()))%3 + 1
    FROM sys.objects
    )
    SELECT TOP 100 
    CASE value_of_rand
        WHEN 1
            THEN 'one'
        WHEN 2
            THEN 'two'
        WHEN 3
            THEN 'three'
        ELSE
            'that is strange'
    END [value_of_case]
    from rndsrc
    

    No more "that is strange"

提交回复
热议问题