如何在将空值插入非空列 SQL 服务器时设置默认值?

How to set default value while insert null value into not null column SQL Server?

我有两个 tables t1t2。两者都有 idname 列。 t1 的名称列被定义为非空,它的默认值为 'Peter'。

我想将 t2 中的所有值插入到我的 t1 table 中。但是我在 t2 table 中有一些空值。当我尝试插入值时:

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.

当我们尝试 insert null 值时,是否有可能为该列设置默认值。

所以不用

Insert into t1 select * from t2

您可以将查询重写为

Insert into t1 
select col1,col2, ISNULL(name, 'Peter'), othercolumns from t2

使用COALESCE

查询

INSERT INTO t1(Id, Name)
SELECT Id, COALESCE(Name, 'Peter') FROM t2;

或者您可以使用 CASE 表达式。

查询

INSERT INTO t1(Id, Name)
SELECT Id, CASE WHEN Name IS NULL THEN 'Peter' ELSE Name END
FROM t2;

第一个解决方案,

   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

将您的查询修改为:

Insert into t1 select COALESCE(column1,'') from t2;

更多详情请参考以下link

http://www.w3schools.com/sql/sql_isnull.asp