How to insert value into primary key column in SQL Server? - sql-server

insert into Student
values('1', 'joedio', 'newyark', GETDATE())
I get this error message when trying to run this SQL:
An explicit value for the identity column in table 'Student' can only be specified when a column list is used and IDENTITY_INSERT is ON.

If you wants to insert primary key by query even it is auto increment then you have to set IDENTITY_INSERT ON as below, it will allow you to insert unique value by query:
SET IDENTITY_INSERT [Tablename] ON;
Your query will be now:
SET IDENTITY_INSERT Student ON;
INSERT INTO Student VALUES('1','joedio','newyark',GETDATE());
SET IDENTITY_INSERT Student OFF;
If you wants that SQL manage it self then default it set to IDENTITY_INSERT OFF and Auto increment is set, means on every insert the new value is assigned to that PK column.
Better to execute with default setting SET IDENTITY_INSERT Student OFF because by manual inset possibility to insert duplicate value and it will throw an error.

If your table has Identity Column, then you have to mention all the other columns while inserting.
Just it is for sample:
INSERT INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE())
If the First column is Identity, then skip the value while inserting:
INSERT INTO Student (Name, State, Date) VALUES('joedio','newyark',GETDATE())
And If you want to Insert Values into an Identity Column in SQL Server
SET IDENTITY_INSERT IdentityTable ON
INSERT INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE())
SET IDENTITY_INSERT IdentityTable OFF
And also refer the link How to Insert Values into an Identity Column in SQL Server for More information.

Try to clear out this concept by taking a look at it.
IDENTITY (Property)
And after mentioning the primary key as identity, you need not to pass an argument for its value. Its value will be auto incremented.

TRY THIS: If you really want to insert value in the IDENTITY column then use one of the given answers as
SET IDENTITY_INSERT [Tablename] ON;
INSERT INTO [Tablename]..........
SET IDENTITY_INSERT [Tablename] OFF;
Otherwise, just get rid off the error exclude the first value from the values
INSERT INTO Student --No need to add column definition if you are inserting rest of all
VALUES('joedio', 'newyark', GETDATE()) --Error Free

In sql server when ID column is Auto Incremental and you are passing ID
IF NOT EXISTS (SELECT * FROM Student WHERE ID = 1)
THEN
SET IDENTITY_INSERT Student ON;
INSERT INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE())
SET IDENTITY_INSERT Student OFF;
END
2.In sql server when ID column is Auto Incremental and you are not passing ID
INSERT INTO Student (Name, State, Date) VALUES('joedio','newyark',GETDATE())
3.In My sql use can use
INSERT IGNORE INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE());
OR
INSERT IGNORE INTO Student (Name, State, Date) VALUES('joedio','newyark',GETDATE());

IDENTITY_INSERT allows explicit values to be inserted into the identity column of a table.
Use this query and set IDENTITY_INSERT on the table 'on'
SET IDENTITY_INSERT Student ON
Note: At any time, only one table in a session can have the IDENTITY_INSERT property set to ON.

SET IDENTITY_INSERT Student ON;
INSERT INTO Student (RegNo, Name, Address, CreatedTime) VALUES('2','calibio','newyark',GETDATE());
SET IDENTITY_INSERT Student OFF;

Related

How can return identity column value from table and insert other table in SQL Server?

I'm beginner in SQL Server and in my database I have two tables:
Table 1 with an id type bigint identity(1, 1)
Table 2 with the columns name and table1ID.
I want to insert (into table 1) and generate an id value. Then I will insert that id value into table1ID of table 2.
i change table to this and write this query:
insert into Interconnect_Traffic_Analysis_MAIN (Code_Op,Name_Op,Shomare_Tel,Duration,table1ID>>table1 id must save in this column)
select t7,t8,t9,t10 from Interconnect_Traffic_Analysis_Temp;
But how can I implement that?
Try this:
-- declare a variable to hold your newly created IDENTITY value
DECLARE #Identity BIGINT
-- insert your values into the first table
INSERT INTO dbo.Table1(list-of-columns)
VALUES(list-of-values);
-- get the newly generated IDENTITY value into your variable
SET #Identity = SCOPE_IDENTITY();
-- use that variable in your second INSERT
INSERT INTO dbo.Table2(table1Id)
VALUES(#Identity)
Update:
With your updated question with the INSERT statement, use this code to include the #Identity value:
INSERT INTO dbo.Interconnect_Traffic_Analysis_MAIN(Code_Op, Name_Op, Shomare_Tel, Duration, table1ID)
SELECT
t7, t8, t9, t10, #Identity
FROM
Interconnect_Traffic_Analysis_Temp;
You can try this:
insert into TableOne values ('abc');
insert into tableTwo values ((select SCOPE_IDENTITY()));
select SCOPE_IDENTITY() goes give you the last inserted id.
See this SQL fiddle

is it possible that an auto increment field duplicates?

I have a table which has several field including:
contact_id
phone
phone_id
contact_id and phone are primary keys and phone_id is an auto increment field. I want to use it to recognize a certain entry. So I want to know that is it possible to duplicate that non primary field when I'm entering data.
Unless there is no constraint, some unique index, you can duplicate values in that column, because 1) you can turn identity_insert on, 2) you can reseed increments.
Here is a proof:
CREATE TABLE #test(id INT IDENTITY(1, 1))
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
SET IDENTITY_INSERT #test ON
INSERT INTO #test(id) VALUES(1)
SET IDENTITY_INSERT #test OFF
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
DBCC CHECKIDENT ('#test', RESEED, 1);
INSERT INTO #test DEFAULT VALUES
INSERT INTO #test DEFAULT VALUES
SELECT * FROM #test
DROP TABLE #test
Output:
id
1
2
3
1
4
5
2
3
The short answer is Yes, it's possible.
SQL Server does not force a unique constraint on identity columns, meaning that the can have duplicated values, however, Sql server will not generate duplicate values itself in an identity column.
Identity columns in sql server are populated by the sql server itself when you insert a row to the table.
However, you can specify a value to them by using SET IDENTITY_INSERT before the insert statement.
There are a couple of things that you should be aware of:
Setting identity_insert on is per table. you can only set it for one table at the time.
Until you set the identity_insert back off, any insert statement to that table will have to specify a value for the identity column.
you can't use set identity insert on for more then one table on a single session. therefor after you've done inserting records to the table you must set the identity_insert back off on that table.

SQL Server 2008 R2: IDENTITY

Q 1:
I have a empty table to insert records. Having one column of IDENTITY type, for which I want to insert values manually.
Example:
Table: Employee
create table Employee
(
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Inserting records:
SET IDENTITY_INSERT Employee ON;
insert into Employee values(101,'ABC','XYZ','HighStreet','Moscow')
Error:
Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'Employee' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Q 2:
How to get latest inserted ID of an Employee without using MAX and Top?
Answer 1
If you will try to insert the value into Identity column you will get the error
Cannot insert explicit value for identity column in table ‘Employee’
when IDENTITY_INSERT is set to OFF.
Write SET IDENTITY_INSERT table name ON before the insert script and
SET IDENTITY_INSERT table name Off after insert script
SET IDENTITY_INSERT Employee ON
insert into Employee(ID,LastName,FirstName,Address,City) values
(101,'ABC','XYZ','HighStreet','Moscow')
SET IDENTITY_INSERT Employee OFF
Answer 2
There are several ways using like this after insert statement
After an INSERT, SELECT INTO, or bulk copy statement is completed,
##IDENTITY contains the last identity value that is generated by the
statement
SELECT ##IDENTITY
It returns the last IDENTITY value produced on a connection,
regardless of the table that produced the value, and regardless of the
scope of the statement that produced the value.
SELECT SCOPE_IDENTITY()
It returns the last IDENTITY value produced on a connection and by a
statement in the same scope, regardless of the table that produced the
value.
SELECT IDENT_CURRENT(‘Employee’)
It returns the last IDENTITY value produced in a table, regardless of
the connection that created the value, and regardless of the scope of
the statement that produced the value. IDENT_CURRENT is not limited by
scope and session; it is limited to a specified table. IDENT_CURRENT
returns the identity value generated for a specific table in any
session and any scope.
MSDN SOURCE
You can use IDENT_CURRENT( 'table_name' ) to get the current value.
For external value of Identity column Column Name given explicitly is Must as below
SET IDENTITY_INSERT Employee ON;
insert into Employee(ID ,LastName,FirstName,Address,City)
values(101,'ABC','XYZ','HighStreet','Moscow')

An explicit value for the identity column in table 'COM_MST' can only be specified when a column list is used and IDENTITY_INSERT is ON

don't know why this code is not executing...
SET IDENTITY_INSERT COM_MST ON
GO
INSERT INTO COM_MST
SELECT * FROM COM_MST_DEL
and showing an error
An explicit value for the identity column in table 'COM_MST' can only be specified when a column list is used and IDENTITY_INSERT is ON.
You have to specify the columns in the insert statement
SET IDENTITY_INSERT COM_MST ON
GO
INSERT INTO COM_MST
SELECT * FROM COM_MST_DEL
In this your select statement SELECT * FROM COM_MST_DEL might be returning more than the column available in table COM_MST also make sure to specify the column name in Insert statement.
OR
See the solution proposed in the post An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

insert issues in an auto increment column

How can I insert data into a column which has been defined as auto increment column using identity insert?please explain with an example.
If you have an "auto-increment" column - you really shouldn't be inserted specific values into that column yourself - after all, that's why it's an auto-increment column....
If you must do so after all - then you need to do:
SET IDENTITY_INSERT (your table name here) ON
INSERT INTO (your table name here) (IdentityCol, OtherCol1, .....)
VALUES( (new ID value), .......)
SET IDENTITY_INSERT (your table name here) OFF

Resources