Insert manually into the table according to the SQL statement, but the key is auto-increment

Let's say I have a user table, and the id column is the primary key and it grows automatically.

I just want to try adding the user manually with this statement:

 INSERT INTO table_name (id, username, password) VALUES (?, Mike, Mike); 

but I do not want to indicate a value ? I just want to add to the next line.

Thanks to everyone, I forgot to set the id column to auto grow. he is working now.

+6
source share
4 answers

So just don't use it ... do it like that.

And don't forget to use single quotes to insert strings

 INSERT INTO table_name (username, password) VALUES ('Mike', 'Mike'); 

As you said, your auto incremented field, SQL will automatically increase the value of the id field by 1

+8
source

If you want to manually insert the value into the auto-add column, you can use IDENTITY_INSERT from sql. eg

 SET IDENTITY_INSERT MyTable ON insert into MyTable(id, name) values (1,'asdf'); insert into MyTable(id, name) values (3,'htgfds'); insert into MyTable(id, name) values (123,'dsfg'); SET IDENTITY_INSERT MyTable OFF 

you can read more here IDENTITY_INSERT

+3
source

If id is a value with the value added automatically, just leave this column outside the insert and it will be filled with the value added automatically. For example, from BOL http://msdn.microsoft.com/en-us/library/aa933196 (v = SQL.80) .aspx

 CREATE TABLE new_employees ( id_num int IDENTITY(1,1), fname varchar (20), minit char(1), lname varchar(30) ) INSERT new_employees (fname, minit, lname) VALUES ('Karin', 'F', 'Josephs') INSERT new_employees (fname, minit, lname) VALUES ('Pirkko', 'O', 'Koskitalo') 
0
source

This should do the job for you:

 INSERT INTO table_name (username, password) VALUES('username_u','password_p'); 

Auto increment value will be automatically added by SQL.

0
source

Source: https://habr.com/ru/post/927141/


All Articles