I have two tables t1
and t2
. Both have id
and name
columns. The name column of t1
is defined as not null and it has the default value of 'Peter'.
I want to insert all the values from t2
into my t1
table. But I have some null values in t2
table. When I try to insert the values:
Insert into t1
select *
from t2;
It throws this error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Name', table 'T1'; column does not allow nulls.
Is there any possibilities to set the default value to the column when we try to insert
the null
value.
Use
COALESCE
Query
Or you can use a
CASE
expression.Query
First Solution,
Second solution
Third Solution :(Best)
So instead of
you can rewrite your query as
Modify your query like:
Insert into t1 select COALESCE(column1,'') from t2;
For more details refer following link
http://www.w3schools.com/sql/sql_isnull.asp