1

the following transact-sql code works properly. it fills up the table with four integers ( 0, 1, 2, 3 ) as expected.

CREATE TABLE [TBL_INTEGER] (
    [ID] INTEGER IDENTITY ( 1, 1 ) PRIMARY KEY,
    [NUMBER] INTEGER NOT NULL
)

DECLARE @MAX INTEGER
SELECT @MAX = 1000

WHILE ( 0 < @MAX ) BEGIN
    INSERT [TBL_INTEGER] ( [NUMBER] ) SELECT ABS ( CHECKSUM ( NEWID () ) ) % 4
    SELECT @MAX = @MAX - 1
END

and the following code does not. it fails generating the 'Cannot insert the value NULL into column 'NUMBER' error.

CREATE TABLE [TBL_INTEGER] (
    [ID] INTEGER IDENTITY ( 1, 1 ) PRIMARY KEY,
    [NUMBER] INTEGER NOT NULL
)

DECLARE @MAX INTEGER
SELECT @MAX = 1000

WHILE ( 0 < @MAX ) BEGIN
    INSERT [TBL_INTEGER] ( [NUMBER] )
        SELECT
            CASE ABS ( CHECKSUM ( NEWID () ) ) % 4
                WHEN 0 THEN 0
                WHEN 1 THEN 1
                WHEN 2 THEN 2
                WHEN 3 THEN 3
            END
    SELECT @MAX = @MAX - 1
END

if i add

ELSE 99

the code does not fail. but one third of the inserted rows contain the value 99.

is there an explanation ?

thank you in advance !

av

  • That is really interesting... I used a different random number generating method with the same results, both as a `case X` and as `case when x = 0`. It seems anytime the calculation is done within the case statement it sometimes misses a beat. Adding in an isnull() caused more nulls, which was interesting... – LordBaconPants Jun 26 '17 at 02:12
  • [This](https://sqlperformance.com/2014/06/t-sql-queries/dirty-secrets-of-the-case-expression) article explains that a searched `CASE` expression may reevaluate the search term. In this example it could happen that the expression is reevaluated for each search value (0, 1, 2, and 3) and none of the four separately computed values matches, hence the default for the `CASE` is `NULL`. Tip: It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. `sql-server-2014`. Differences in syntax and features often affect the answers. – HABO Jun 26 '17 at 03:44
  • dear @habo, thank you for the article ! it explains my code's behavior. – andrey vladimirsky Jun 26 '17 at 11:50

0 Answers0