I am trying to add NOT NULL and a DEFAULT to an existing table.
To do this, I am using a transitional table to populate any NULL values.
Table1 has the NULL column, Table2 has the improved design.
CREATE TABLE table1 (
CustomerID INT
, CartID NULL);
CREATE TABLE table2 (
CustomerID INT
, CartID NOT NULL DEFAULT NEWID());
INSERT INTO table2 (CustomerID, CartID)
SELECT CustomerID, CartID = CASE CartID WHEN NULL THEN NEWID() ELSE CartID END
FROM table1;
I still get the “Cannot insert the value NULL into column” error, even though I am populating every NULL value with a new value in the SELECT statement.
How can I make this work?
In
SQL,NULLis not equal toNULL(and not unequal too).This is why
CASE var WHEN NULL THEN …will never succeed.Use this:
or just this: