我有两个表t1
和t2
。两者都有 id
和 name
列。 t1
的 name 列定义为非空,并且默认值为“Peter”。
我想将 t2
中的所有值插入到我的 t1
表中。但我在 t2 表中有一些空值。当我尝试插入值时:
Insert into t1
select *
from t2;
它抛出此错误:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Name', table 'T1'; column does not allow nulls.
当我们尝试插入
null
值时,是否有可能为该列设置默认值。
最佳答案
第一个解决方案,
insert into t1
select id,isnull(name,'Peter') from t2
第二种解决方案
ALTER TABLE T1 ALTER COLUMN name varchar(255) NULL
insert into t1
select id,name from t2
ALTER TABLE T1 ALTER COLUMN name varchar(255) NOT NULL
关于sql - SQL Server 将空值插入非空列时如何设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36735045/