Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into table with specific primary key identity (1,1)

Tags:

sql

sql-server

Like a table, we always prefer to make identity as primary key like identity(1,1) That way, that column will start 1 increment 1 when adding new row.

So could I ask whether I can add one row with specified number manually, like I can add one row with primary key 100

like image 822
Hypnoz Avatar asked Sep 05 '12 15:09

Hypnoz


People also ask

How do you make an identity column start from 1?

CREATE TABLE school ( student_id INT IDENTITY, student_name VARCHAR(200), marks INT ); Here, the 'student_id' column of the table starts from 1 as the default value of seed is 1 and each row is incremented by 1.

Can we use 2 primary keys in a table?

Each table can only have one primary key. Access can automatically create a primary key field for you when you create a table, or you can specify the fields that you want to use as the primary key.


2 Answers

set Identity_Insert yourtable on

Then do the insert

insert yourtable (id, field) values(100,'hello')

Then turn it off again

set Identity_Insert yourtable off
like image 147
podiluska Avatar answered Nov 05 '22 14:11

podiluska


Yes you can. Using SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }:

SET IDENTITY_INSERT YourTable ON

INSERT YourTable(Id, OtherField)
VALUES (100, 'Other Value')

SET IDENTITY_INSERT YourTable OFF
like image 32
Mahmoud Gamal Avatar answered Nov 05 '22 14:11

Mahmoud Gamal