Error trying to insert SQL SERVER

Asked

Viewed 3,084 times

0

I created a table in the BD with the following code

CREATE TABLE documentosDefesa
(
id_documentos_defesa int NOT NULL,
id_reclamatoria int NOT NULL,
funcao nvarchar(50) NULL
);

And now when I try to make the following insertion,:

INSERT INTO [RDO].[dbo].[documentosDefesa] (id_reclamatoria, funcao) VALUES (177,'Pedreiro')

in SQL SERVER MANAGEMENT it displays the following warning:

Cannot insert NULL value in column 'id_documents_defense', table 'RDO.dbo.documentsDefesa'; column does not allow nulls. INSERT failure.

I don’t understand why I made a mistake, because it’s not the first time I’ve created a table and I do it!

  • That field is identity?

  • 2

    The camp was created as int NOT NULL so it can’t be null. I think it should be declared as identity and not int

  • No... How should I proceed then? I change the field to int Identity?

  • But the system itself is responsible for putting value in this field, right?

  • Yes, if it is identity

  • Right. So, just change the field? Put Identity?

  • 1

    It must be declared so: id_documentos_defesa int IDENTITY(1,1) PRIMARY KEY,

  • Thanks guys, it worked out

Show 3 more comments

1 answer

4


The way you created your table, it is set that the id_documents_defense field cannot be null, and at the time of inserting, you are not specifying value for such field (which cannot be null).

Perhaps you expected this field to be auto-incremented. For that, you would have to create your table as follows:

CREATE TABLE documentosDefesa
(
    id_documentos_defesa int IDENTITY(1,1) PRIMARY KEY,
    id_reclamatoria int NOT NULL,
    funcao nvarchar(50) NULL
);

Or change the SQL statement. for example:

INSERT INTO [RDO].[dbo].[documentosDefesa] (id_documentos_defesa, id_reclamatoria, funcao) VALUES (1, 177,'Pedreiro')

If you don’t want to delete the whole table, you can only change the ID column:

ALTER TABLE documentosDefesa DROP COLUMN id_documentos_defesa;
ALTER TABLE documentosDefesa ADD id_documentos_defesa int IDENTITY(1,1);
  • But it is for the system to put id value in these @P. Santos fields, not me hehehe

  • 2

    But that’s what the answer teaches you to do, @Gustavo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.