Не удалось вставить значение null ошибка в insert

I’m using the following query:

INSERT INTO role (name, created) VALUES ('Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

However, I’m not specifying the primary key (which is id). So my questions is, why is sql server coming back with this error:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'id', table 'CMT_DEV.dbo.role'; column does not allow nulls. INSERT fails.
The statement has been terminated.

James Drinkard's user avatar

asked Apr 4, 2012 at 14:33

Ben's user avatar

0

I’m assuming that id is supposed to be an incrementing value.

You need to set this, or else if you have a non-nullable column, with no default value, if you provide no value it will error.

To set up auto-increment in SQL Server Management Studio:

  • Open your table in Design
  • Select your column and go to Column Properties
  • Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1

answered Apr 4, 2012 at 14:36

Curtis's user avatar

CurtisCurtis

101k65 gold badges269 silver badges351 bronze badges

3

use IDENTITY(1,1) while creating the table
eg

CREATE TABLE SAMPLE(
[Id]     [int]  IDENTITY(1,1) NOT NULL,
[Status] [smallint] NOT NULL,

CONSTRAINT [PK_SAMPLE] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)
)

Nick's user avatar

Nick

1,1583 gold badges24 silver badges36 bronze badges

answered Jan 9, 2018 at 19:41

Minakshi Korad's user avatar

If the id column has no default value, but has NOT NULL constraint, then you have to provide a value yourself

INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

answered Apr 4, 2012 at 14:40

Andy Irving's user avatar

Andy IrvingAndy Irving

2,6571 gold badge14 silver badges11 bronze badges

Encountered the same issue. This is something to do with your table creation. When you created table you have not indicate ‘ID‘ column to be Auto Increment hence you get this error. By making the column Primary Key it cannot be null or contain duplicates hence without Auto Increment pretty obvious to throw column does not allow nulls. INSERT fails.

There are two ways you could fix this issue.

1). via MS SQL Server Management Studio

  1. Got to MS SQL Server Management Studio

  2. Locate your table and right click and select Design

  3. Locate your column and go to Column Properties

  4. Under Indentity Specification: set (Is Identity)=Yes and Indentity
    Increment=1

2). via ALTER SQLs

ALTER TABLE table DROP COLUMN id; // drop the existing ID
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

answered Dec 15, 2022 at 7:02

Du-Lacoste's user avatar

Du-LacosteDu-Lacoste

11.3k2 gold badges67 silver badges50 bronze badges

0

You either need to specify an ID in the insert, or you need to configure the id column in the database to have Identity Specification = Yes.

answered Apr 4, 2012 at 14:38

JupiterP5's user avatar

JupiterP5JupiterP5

3181 silver badge10 bronze badges

As id is PK it MUST be unique and not null.
If you do not mention any field in the fields list for insert it’ll be supposed to be null or default value.
Set identity (i.e. autoincrement) for this field if you do not want to set it manualy every time.

answered Apr 4, 2012 at 14:38

quzary's user avatar

quzaryquzary

2851 silver badge4 bronze badges

You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.

answered Apr 4, 2012 at 14:44

RisingDragon's user avatar

you didn’t give a value for id. Try this :

INSERT INTO role (id, name, created) VALUES ('example1','Content Coordinator', GETDATE()), ('example2', 'Content Viewer', GETDATE())

Or you can set the auto increment on id field, if you need the id value added automatically.

answered May 9, 2017 at 2:04

natadecoco's user avatar

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) — meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

answered Nov 1, 2019 at 15:22

vid.dev's user avatar

WARNING! Make sure the target table is locked when using this method
(As per @OnurOmer’s comment)

if you can’t or don’t want to set the autoincrement property of the id, you can set value for the id for each row like this:

INSERT INTO role (id, name, created)
SELECT 
      (select max(id) from role) + ROW_NUMBER() OVER (ORDER BY name)
    , name
    , created
FROM (
    VALUES 
      ('Content Coordinator', GETDATE())
    , ('Content Viewer', GETDATE())
) AS x(name, created)

answered Apr 16, 2018 at 2:13

robotik's user avatar

robotikrobotik

1,7981 gold badge19 silver badges24 bronze badges

2

RULE: You cannot IGNORE those colums that do not allow null values, when inserting new data.

Your Case

  • You’re trying to insert values, while ignoring the id column, which does not allow nulls. Obviously this won’t work.
  • Gladly for you the «Identity Specification» seems to automatically fill the not nullable id values for you (see selected answer), when you later execute the insert query.

My Case

  • The problem (while using SSMS): I was having this error when trying to add a new non-nullable column to an already existing table with data. The error I’d got was:

Cannot insert the value NULL into column ‘id_foreign’, table ‘MyDataBase.dbo.Tmp_ThisTable’; column does not allow nulls. INSERT fails.
The statement has been terminated.

  • The solution:
    1. I created the column I needed id_foreign, allowing nulls.
    2. I edited/inserted all the required values for id_foreign.
    3. Once the values where in place, I went back and unchecked the «Allow Nulls» checkbox. Now the error was gone.

answered Jul 26, 2022 at 14:54

carloswm85's user avatar

carloswm85carloswm85

1,24813 silver badges21 bronze badges

I have set some script that inserts data from an XML file into a SQL database. I am getting the following error.

Cannot insert the value NULL into column 'fighterID', table 'MMA     Database.dbo.FIGHTERStemp'; column does not allow nulls. INSERT fails.

I have fighterID set as the primary key and will not allow NULLS. My intention is to have it number each row as they are inserted. I found one answer that advises to modify the column properties to be the identifier. However it will not let me adjust the columns properties without dropping and adding the table again.

I can do that — but what is the SQL syntax to set the identity specification settings? Am I going about this the right way?

asked Dec 16, 2015 at 2:30

Jason Vondersmith's user avatar

1

It’s pretty simple, just set the field with datatype INT (integer) and follow it with keyword IDENTITY. You can include the seed and increment values; e.g. start at 1, increment by 1, or just use the keyword IDENTITY for a 1,1 default.

CREATE TABLE MMA (FighterID INT IDENTITY (1,1), FighterInfo VARCHAR(MAX))

answered Dec 16, 2015 at 2:38

Steve Mangiameli's user avatar

3

While inserting data into Primary key you can check the previous max id value and then increment it to next value before you insert a new row.

In SQL, you need to drop table before altering its specification. You can do this by taking backup into temp table then drop your main table and then re insert data from temp table.

answered Dec 16, 2015 at 2:41

Avi's user avatar

AviAvi

1,1158 gold badges19 silver badges30 bronze badges

1

1
2
3
4
5
6
7
8
9
10
11
   INSERT INTO Students (FIO,Data_Rozhd,Adres,Telephon,Pasport_dani,Nomer_zachetki,Data_postyplenia,
 Nomer_group,Kours)  VALUES
 ('Іванов С.В.','1990-12-23','м.Київ','+380937889876','АН856756','08ВП129','2010-06-26','2101','3'),
 ('Давидова В.В.','1990-05-17','м.Дніпро','+380957895674','АН456776','08ВП130','2010-06-26','2101','3'),
 ('Сластов В.В.','1990-11-02','м.Запоріжжя','+093462875690','АН543809','08ВП131','2010-06-26','2101','3'),
 ('Коптіякіна М.В.','1992-01-71','м.Кіровоград','+068027868909','АН856756','08ВП132','2011-06-28','2102','2'),
 ('Денисюк М.М.','1993-12-01','м.Луганськ','+067168563470','АН231267','08ВП133','2011-06-28','2102','2'),
 ('Андрущак В.В.','1992-05-23','м.Киев','+067569098723','АН874385','08ВП134','2011-06-28','2102','2'),
 ('Драгун В.І.','1991-04-02','м.Харків','+073462234769','АН654383','08ВП135','2006-06-14','2103','4'),
 ('Яковлева О.С.','1991-07-23','м.Донецьк','+073027874638','АН213389','08ВП136','2006-06-14','2103','4'),
 ('Гордієнко В.М.','1992-04-15','м.Львів','+097780562234','АН276963','08ВП137','2006-06-14','2103','4');

Have you gotten the “ORA-01400: cannot insert null into (string)” error? Learn what causes this and how to resolve it in this article.

ORA-01400 Cause

If you try to run an INSERT statement to insert data into a table, you may get this error.

ORA-01400: cannot insert NULL into (string)

In Oracle databases, you can store a NULL value in any column of any data type, as long as the column is not defined as “NOT NULL” or is a primary key.

A NULL value is not the same as 0 or an empty string of ”.

When you attempt to insert a record into a table, and a value of NULL is being inserted into a column that does not allow NULL values, then this error will occur.

To resolve the ORA-01400 error, you have a few options:

  1. Change your INSERT statement so it inserts a value that is not NULL
  2. Change your table definition so that it allows for NULL values.

Let’s take a look at these solutions in more detail.

Solution 1: Adjust your INSERT Statement

To avoid the ORA-01400 error, you can adjust your INSERT statement to ensure that a non-NULL value is inserted.

Let’s see an example of this.

We have a customer table here:

CREATE TABLE customer (
  customer_id NUMBER PRIMARY KEY,
  customer_name VARCHAR2(100) NOT NULL,
  email_address VARCHAR2(400)
);

The customer_id has been set as the primary key, which means it cannot take NULL values.

The customer_name field has the words NOT NULL after it. This means a NOT NULL constraint has been applied and NULL values are not allowed in this column.

The email_address column is allowed NULL values.

Now, let’s try insert a value.

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (1, 'John', '[email protected]');

This value is inserted successfully.

Now, let’s try specify a NULL value for the customer_name:

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (2, NULL, '[email protected]');
SQL Error: ORA-01400: cannot insert NULL into ("INTRO_USER"."TEST_CUSTOMER"."CUSTOMER_NAME")
01400. 00000 - "cannot insert NULL into (%s)"
*Cause: An attempt was made to insert NULL into previously listed objects.
*Action: These objects cannot accept NULL values.

The error appears because a NULL value is specified for the customer_name column, which is not allowed to have NULL values.

This could also happen with this statement. We have not specified the customer_name field in the INSERT statement columns, so a NULL value is used.

INSERT INTO customer (customer_id, email_address)
VALUES (3, '[email protected]');
SQL Error: ORA-01400: cannot insert NULL into ("INTRO_USER"."TEST_CUSTOMER"."CUSTOMER_NAME")
01400. 00000 - "cannot insert NULL into (%s)"
*Cause: An attempt was made to insert NULL into previously listed objects.
*Action: These objects cannot accept NULL values.

To resolve this, we need to ensure that a value of NULL is not added into this column.

Change the value of customer_name to something that is not NULL:

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (3, 'Sarah', '[email protected]');

Or, if you’re getting data from another source, surround your value with the NVL function, which translates a NULL value to something else.

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (3, NVL(input_name, 'Unknown'), '[email protected]');

If your values are coming from another system or source and definitely should not be NULL, then you might need to investigate the source of the data to find out why the values are NULL.

Solution 2: Change the Table Definition

Another way to resolve the ORA-01400 error is to change the definition of the table so that it allows for NULL values.

You can do this using the ALTER TABLE statement.

For example, to remove the NOT NULL constraint from the customer_name field in the customer table (mentioned above), you can run this command:

ALTER TABLE customer MODIFY COLUMN customer_name VARCHAR2(100);

This will remove the NOT NULL constraint from the table.

Now, you can insert a NULL value into this column.

INSERT INTO customer (customer_id, customer_name, email_address)
VALUES (4, NULL, '[email protected]');

Conclusion

So, that’s how you can resolve the ORA-01400 error.

It’s caused by inserting a NULL value into a column that cannot be NULL.

You can resolve it by adjusting your INSERT statement or modifying your table.

 Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

В процессе обновления информационной базы произошла критическая ошибка по причине: Ошибка СУБД: Microsoft SQL Server Native Client 11.0: Не удалось вставить значение NULL в столбец таблицы «.dbo.»; в столбце запрещены значения NULL. Ошибка в INSERT.

Описание ошибки:
Столкнулся с ошибкой при выполнении процедуры Тестирование и исправление… на этапе реструктуризации таблиц информационной базы. База клиент-серверная. 1С: Управление торговлей 10.3.31. Платформа 1С: Предприятие 8.3.9

Найденные решения:

Сложно сказать, что посчастливилось, но все же ошибка преследовала меня в базе не единожды. Но по своей сути каждая последующая формулировка «В процессе обновления информационной базы произошла критическая ошибка…» отличалсь в причине и решении незначительно. С такой ошибкой столкнулся, если быть откровенным, впервые, но интернет в принятии решения устранения ошибки сильно не помог, кроме вот этого обсуждения на форуме Как удалить строки содержащие NULL в таблице где NULL недопустимо. Зацепок решения не было. Но все же решение было найдено. Читаем… ниже.

1С 8 ошибки в конфигураторе тестирование и исправление базы данных, В процессе обновления информационной базы произошла критическая ошибка

Итак, начнем с первого факта возникновения ошибки при выполнении тестирования и исправления базы данных на этапе реструктуризации таблиц базы данных.

1С 8 критическая ошибка по причине: Ошибка СУБД: Microsoft SQL Server Native Client 11.0: Не удалось вставить значение NULL в столбец , таблицы   ".dbo."; в столбце запрещены значения NULL. Ошибка в INSERT.

Кнопка «Подробно…»:

1С 8, конфигуратор, тестирование, как исправить ошибку HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1

Полный текст ошибки:
В процессе обновления информационной базы произошла критическая ошибка
по причине:
Ошибка СУБД:
Microsoft SQL Server Native Client 11.0: Не удалось вставить значение NULL в столбец «_Fld412», таблицы «Торговля.dbo._Reference19NG»; в столбце запрещены значения NULL. Ошибка в INSERT.
HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1

Если взглянуть скрином ранее, то нельзя упустить из виду подсказку, оставленую программой в левом нижнем углу окна программы, в строке состояния, о том, что выполнение реструктуризации прервалось на справочнике «Банковские счета». В базе справочник имел более 3х с половиной тысяч элементов, поэтому сходу было сложно понять, в каком из них скрывается ошибка. Была написана простая обработка, которая просто должны была обойти все элементы справочника и перезаписать их. Надежда была на то, что запись проблемного элемента завершиться ошибкой.

Исполняемый код обработки прост:

Запрос = Новый Запрос;
Запрос.Текст = «ВЫБРАТЬ
               | БанковскиеСчета.Ссылка
               |ИЗ
               | Справочник.БанковскиеСчета КАК БанковскиеСчета»;
Выборка = Запрос.Выполнить().Выбрать();
Пока Выборка.Следующий() Цикл
       СпрОбъект = Выборка.Ссылка.ПолучитьОбъект();
       СпрОбъект.Записать();
КонецЦикла;

Предположение было оправдано. Ошибка при записи возникла. Теперь было понятно, элемент с каким кодом может быть причиной критической ошибки в процессе обновления информационной базы.

1C 8 как исправить ошибку при тестировании и исправлении в конфигураторе В процессе обновления информационной базы произошла критическая ошибка по причине: Ошибка СУБД: Microsoft SQL Server Native Client 11.0

Это оказался элемент справочника, у которого не был заполнен ни одни реквизит, так что мне даже не удавалось пометить такой элемент на удаление. Дальше была написана простая обработка для удаления выбранного элемента справочника без проверки ссылочной целостности. Элемент был удален.

Тестирование и исправление было запущено повторно. Но уже вскоре после запуска процедуры в режиме реструктуризация таблиц базы мен ожидала идентичная ошибка, но уже связанная со справочником «Организации».

Новый текст ошибки отличался лишь немногим, названием таблицы и именем столбца:
В процессе обновления информационной базы произошла критическая ошибка
по причине:
Ошибка СУБД:
Microsoft SQL Server Native Client 11.0: Не удалось вставить значение NULL в столбец «_Fld888», таблицы «Торговля.dbo._Reference66NG»; в столбце запрещены значения NULL. Ошибка в INSERT.
HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1

1С 8 ошибка в конфигураторе как исправить Не удалось вставить значение NULL в столбец "_Fld888", таблицы   "Торговля.dbo._Reference66NG"; в столбце запрещены значения NULL. Ошибка в INSERT.

По опыту предыдущей инцидента уже казалось понятным, что в справочнике у какого-то элемента не заполнены данные. Так и оказалось. Проблемный элемент справочника был найден мгновенно и в этом случае повезло больше элемент можно было пометить на удаление, был помечен и удален с помощью «Удаление помеченных объектов».

1С предприятие 8 ошибка при тестировании базы как устранить HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1

Тестирование и исправление было запущено в третий раз. Но и этот раз не обошелся без «критической ошибки в процессе обновления информационной базы».

Текст третьей ошибки:
В процессе обновления информационной базы произошла критическая ошибка
по причине:
Ошибка СУБД:
Microsoft SQL Server Native Client 11.0: Не удалось вставить значение NULL в столбец «_Fld1024RRef», таблицы «Торговля.dbo._Reference88NG»; в столбце запрещены значения NULL. Ошибка в INSERT.
HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1

1С 8 конфигуратор ошибка при тестировании и исправлении, реструктуризация таблиц информационной базы, В процессе обновления информационной базы произошла критическая ошибка по причине: Ошибка СУБД:

Но и в этот раз программа оставила подсказку, что проблема содержится в записях справочника «ТипыЦенНоменклатурыКонтрагентов».

Удалить проблемные элементы справочника пришлось программно с помощью все той же, указанной выше простой обработки непосредственного удаления без проверки ссылочной целостности.

1С 8 ошибка конфигуратора Microsoft SQL Server Native Client 11.0: Не удалось вставить значение NULL в столбец таблицы   dbo, в столбце запрещены значения NULL. Ошибка в INSERT. HRESULT=80040E2F, SQLSrvr: SQLSTATE=23000, state=2, Severity=10, native=515, line=1

И в итоге очередной запуск, уже четвертый по счету, в режиме «Реструктуризация таблиц информационной базы» в рамках тестирования и исправления завершился успешно.

Оцените, помогло ли Вам предоставленное описание решения ошибки?




© www.azhur-c.ru 2014-2020. Все права защищены. Использование текстов и изображений с данной страницы без письменного разрешения владельца запрещено. При использовании материалов с данной страницы обязательно указание ссылки на данную страницу.

31-10-2018

Журавлев А.С.
(Сайт azhur-c.ru)

Понравилась статья? Поделить с друзьями:
  • Не удалось восстановить айфон произошла неизвестная ошибка 4010
  • Не удалось восстановить айфон произошла неизвестная ошибка 4005
  • Не удалось восстановить айфон произошла неизвестная ошибка 3194
  • Не удалось восстановить айфон произошла неизвестная ошибка 3014
  • Не удалось восстановить айфон произошла неизвестная ошибка 2006