简体   繁体   English

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

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

I have two tables t1 and t2 .我有两个表t1t2 Both have id and name columns.两者都有idname列。 The name column of t1 is defined as not null and it has the default value of 'Peter'. t1的名称列被定义为非空并且它的默认值为“Peter”。

I want to insert all the values from t2 into my t1 table.我想将t2所有值插入到我的t1表中。 But I have some null values in t2 table.但是我在t2表中有一些空值。 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消息 515,级别 16,状态 2,第 1 行
Cannot insert the value NULL into column 'Name', table 'T1';无法将值 NULL 插入列 'Name'、表 '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.当我们尝试insert null值时,是否有可能为列设置默认值。

First Solution,第一个解决方案,

   insert into t1
    select id,isnull(name,'Peter') from t2

Second solution第二种解决方案

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

So instead of所以代替

Insert into t1 select * from t2

you can rewrite your query as您可以将查询重写为

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

Use COALESCE使用COALESCE

Query查询

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

Or you can use a CASE expression.或者您可以使用CASE表达式。

Query查询

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

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 http://www.w3schools.com/sql/sql_isnull.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM