Cannot insert the value NULL into column where using Sql Select statement

流过昼夜 提交于 2019-12-02 11:52:26

As @jamieD77 commented you are missing the IsDeleted column in your insert statement.

The error means that the column is marked as "NOT NULL" and therefore a value must be inserted when a new row is created.

So you either need to remove the NULL constraint from the table yourself or insert a value in the column.

 INSERT INTO [Migrated].[dbo].[Cities] (Name, ZipCode, IsDeleted)
 select  DISTINCT a.City,a.ZipCode,0 from [Legacy].[dbo].[Ziplist] as a where ( 
 a.City is not null and a.ZipCode is not null);

For a bit field which I would assume it is (but you should confirm!) the value 0 would be false and 1 would be true. If the field is a different data type these values may have different meanings!!!

What the error message says is that the IsDeleted column is declared NOT NULL and it does not have a default value. In this case, you are probably inserting non-deleted records by default, so you might want to change column:

alter table cities alter column IsDeleted int not null default 0;

Alternatively, you can write the query to include the column:

INSERT INTO [Migrated].[dbo].[Cities] (Name, ZipCode, IsDeleted)
    select  DISTINCT zl.City, zl.ZipCode, 
    from [Legacy].[dbo].[Ziplist] zl
    where a.City is not null and a.ZipCode is not null;

These answers assume that IsDeleted is an integer with "0" for false. If the values are stored differently, then the code needs to be modified appropriately.

Simply add the column to insert list and fixed value to select list.

INSERT INTO [Migrated].[dbo].[Cities] (Name, ZipCode, IsDeleted)
select  DISTINCT a.City,a.ZipCode, 0 IsDeleted --0 means false
  from [Legacy].[dbo].[Ziplist] as a 
    where (a.City is not null and a.ZipCode is not null);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!