Friday, March 14, 2014

Cannot insert the value NULL into column '', table ' '; column does not allow nulls. UPDATE fails.

To Get the same error i execute the below queries on schema scott.emp
here we need to make the column not null first to get the same error.

alter table emp alter column job nvarchar(20) not null;

Insert some unmatched record:
insert into emp values (3434,'GURJEET',0,7782,getdate(),1920,null,10);
 
update emp
set job = case when job = 'CLERK' then 1
                when job = 'SALESMAN' then 2
                when job = 'MANAGER' then 3
                when job = 'ANALYST' then 4
                when job = 'PRESIDENT' then 5 end

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column '', table ' '; column does not allow nulls. UPDATE fails.
The statement has been terminated.   
   
SOLUTION:1. Use of where clause
We can use the "where" clause for update query to restrict the records, which are not mentioned in "case statement". In below query i handle the record of having "JOB=0"

update emp
set job = case when job = 'CLERK' then 1
                when job = 'SALESMAN' then 2
                when job = 'MANAGER' then 3
                when job = 'ANALYST' then 4
                when job = 'PRESIDENT' then 5 end
where job not in ('0');           
(14 row(s) affected)

SOLUTION:2. Use of "ELSE" in "CASE statement", Again we add the else in CASE Statement to handle unmatched record.

update emp
set job = case when job = 'CLERK' then 1
                when job = 'SALESMAN' then 2
                when job = 'MANAGER' then 3
                when job = 'ANALYST' then 4
                when job = 'PRESIDENT' then 5 else 0 end;
(14 row(s) affected)

No comments:

Post a Comment

web stats