15

Let's say I have a table of users and the id column is the primary key and auto incremented.

I want to just try and add user manually by this statement:

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

but I don't want to specify the ? value, just want to add to the next row.

Thanks everyone, I forgot to set the id column to auto increment. it works now.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mike
  • 1,302
  • 6
  • 23
  • 43

4 Answers4

15

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

And be sure you use single quotes for inserting strings

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

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

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
12

If you want to manually insert a value to an auto incremented column you can use the IDENTITY_INSERT of sql. for example

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

Mr T.
  • 4,278
  • 9
  • 44
  • 61
1

If id is a auto incremented value just leave that column out of the insert and it will fill in with the auto incremented value. 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')
Kuberchaun
  • 29,160
  • 7
  • 51
  • 59
1

This should do the job for you:

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

The autoincrement value will be automatically added by SQL.

krishnang
  • 698
  • 1
  • 7
  • 21