I have a SQL Server table that I am building with over 100 columns. I am running UPDATE TABLE_NAME queries to populate that table. However, if there are no records available, a NULL is inserted into the record. This makes the calculations that I must perform difficult .
I tried creating the table with NOT NULL and DEFAULT (0) in the CREATE TABLE statement, but when I run an update, it tries to insert a NULL value and I get this error:
Update Statement:
UPDATE TABLE_NAME
SET NumOrders = (SELECT count(OrderID) FROM ORDERS WHERE TABLE_NAME.CUSTOMER_ID = ORDERS.CUSTOMER_ID);
Cannot insert the value NULL into column 'NumOrders', table 'TABLE_NAME'; column does not allow nulls. UPDATE fails.
I could run a 2nd update query to remove the NULLS, such as:
UPDATE TABLE_NAME
SET NumOrders = 0
WHERE NumOrders IS NULL;
This seems like I am doubling up on the update queries I have to write.
There has to be a better way to do this, right….?
Thanks
does this work for you?