WITH SillySequence (Ordinal) AS (
SELECT 1
UNION ALL
SELECT (1 + Ordinal) FROM SillySequence WHERE Ordinal < 100
)
SELECT
NeverNull =
CHOOSE(
RandomValue,
'one', 'two'),
SometimesNull =
CHOOSE(
1 + ABS(CHECKSUM(NEWID()) % 2),
'one', 'two')
FROM (
SELECT RandomValue = 1 + ABS(CHECKSUM(NEWID()) % 2)
FROM SillySequence
) _
Here are few notes:
SillySequence
exists solely to produce 100 records.1 + ABS(CHECKSUM(NEWID()) % 2)
produces (at random) either 1 or 2.NeverNull
is, well, neverNULL
. The only difference betweenNeverNull
andSometimesNull
is that the first argument forNeverNull
'sCHOOSE
function is calculated inside a separate subquery.NULL
values are never produced when using% 1
. To produceNULL
, the divisor must be 2 or greater.
The following example chooses between 5, 6, and NULL
at random. It never chooses any of the other values, which leads me to believe that ABS(CHECKSUM(NEWID()) % 2)
is occasionally producing NULL
when directly provided as an argument to CHOOSE
.
WITH SillySequence (Ordinal) AS (
SELECT 1
UNION ALL
SELECT (1 + Ordinal) FROM SillySequence WHERE Ordinal < 100
)
SELECT
SometimesNull =
CHOOSE(
5 + ABS(CHECKSUM(NEWID()) % 2),
1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
FROM SillySequence
Interestingly, I can always trigger a "severe" error with the following:
SELECT CHOOSE(
(SELECT 1 + ABS(CHECKSUM(NEWID()) % 2)),
'one', 'two')
Msg 0, Level 11, State 0, Line 20
Cannot continue the execution because the session is in the kill state.
Msg 0, Level 20, State 0, Line 20
A severe error occurred on the current command. The results, if any, should be discarded.
I've tested the examples above in SQL Server 2016 using compatibility levels 110
, 120
, and 130
.