在非null列SQL Server中插入null值时如何设置默认值? [英] How to set default value while insert null value into not null column SQL Server?

查看:140
本文介绍了在非null列SQL Server中插入null值时如何设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表 t1 t2 。两者都有 id name 列。 t1 的名称列定义为不为空,其默认值为'Peter'。

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想要将 t2 中的所有值插入我的 t1 表中。但是我在 t2 表中有一些空值。当我尝试插入值时:

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;

它引发此错误:


消息515,级别16,状态2,第1行

无法将值NULL插入表 T1的名称列中;列不允许为空。

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

第三种解决方案:(最佳)

Third Solution :(Best)

    Declare @GetDefaultValue varchar(255)

    SELECT  @GetDefaultValue= COLUMN_DEFAULT
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'dbo'
      AND TABLE_NAME = 'T1'
      AND COLUMN_NAME = 'name'


 insert into t1 select id,isnull(name,@GetDefaultValue) from t2

这篇关于在非null列SQL Server中插入null值时如何设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆