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

时光怂恿深爱的人放手 提交于 2019-12-07 04:47:12

问题


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.


回答1:


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

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



回答2:


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



回答3:


Use COALESCE

Query

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

Or you can use a CASE expression.

Query

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



回答4:


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



来源:https://stackoverflow.com/questions/36735045/how-to-set-default-value-while-insert-null-value-into-not-null-column-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!