Can you make inserting by Id optional? - sql

I want to be able to insert something into my table at a specific ID, so I turned IDENTITY_INSERT on for the table. However, if I just want the auto increment to handle the ID, this error appears:
"Explicit value must be specified for identity column in table
'TsiList' either when IDENTITY_INSERT is set to ON or when a
replication user is inserting into a NOT FOR REPLICATION identity
column."
Is there a way to make the queries
INSERT INTO table (ID, something_else) VALUES (15, 'foo');
and
INSERT INTO table (something_else) VALUES ('foo');
work at the same time?

You can't do it without switching identity_insert on and off as required in between running each query.
Each version will only work when identity_insert is set to the relevant value within the session in which the query is being executed.
For example:
SET IDENTITY_INSERT TsiList ON;
INSERT INTO TsiList (ID, something_else) VALUES (15, 'foo');
SET IDENTITY_INSERT TsiList OFF;
INSERT INTO TsiList (something_else) VALUES ('foo');

Related

linked server set identity_insert

Need to insert from table to another in linked server, need to insert "ID" also in table ,
Can't using identity_insert on linked server, tried every thing
set identity_insert [10.10.10.10].[POS_KIG].[dbo].[Colors] on
insert into [10.10.10.10].[POS_KIG].[dbo].[Colors]
select * from [POS_KIG].[dbo].[Colors] Colors where Colors.ID not In (select HostColor.ID from [10.10.10.10].[POS_KIG].[dbo].[Colors] HostColor)
set identity_insert [10.10.10.10].[POS_KIG].[dbo].[Colors] off

Inserting values when identity is on

I have a table with identity(1,1) field and i want to use insert into to insert values into it.
How can I insert values into the indentity field?
Thank you!
SET IDENTITY_INSERT tbl ON
-- insert (include the ID column)
SET IDENTITY_INSERT tbl OFF
you've got to do this:
SET IDENTITY_INSERT TableNameHere ON
then you can insert values into it:
SET IDENTITY_INSERT IdentityTable ON
INSERT IdentityTable(TheIdentity, TheValue)
VALUES (3, 'First Row')
SET IDENTITY_INSERT IdentityTable OFF
If your question is actually how you get the system to supply appropriate values in the identity column, the answer is that you just don't mention it in your insert query:
INSERT INTO Table (ColumnA_That_Isnt_Identity,ColumnB_That_Isnt_Identity)
VALUES (9,'abc')
And then the IDENTITY column will be assigned a value automatically.
If you want to know what value was assigned to this column, you can either query SCOPE_IDENTITY as a separate SELECT or include an OUTPUT clause, as here:
INSERT INTO Table (ColumnA_That_Isnt_Identity,ColumnB_That_Isnt_Identity)
OUTPUT inserted.ID_Column_That_Is_The_Identity
VALUES (9,'abc')
When IDENTITY_INSERT is ON, you're telling the system "trust me, I'll supply an appropriate value". When it's OFF, you're telling the system to supply the value. Those are your two choices.
There's no means to, on the one had, set IDENTITY_INSERT as ON, and, whilst that is set, request that the system provide a value. Given that IDENTITY_INSERT has only a single purpose, to allow you to provide the values, this should never be a problem.

How to insert a new record in a table by MAX(ID) + 1 of the same table

I have a table CMT_M_DISPOSITION (DispositionKey, DispositionValue). PK is on DispositionKey. I wish to insert a new record by using MAX(DispositionKey) + 1 for the first column.
I get an error
Invalid column DispositionKey
when I run the below code.
Can anybody explain why I am getting this error and how to resolve it?
SET IDENTITY_INSERT EY_CMT_TestV2..CMT_M_DISPOSITION ON
Insert into CMT_M_DISPOSITION (DispositionKey, DispositionValue)
values (MAX(DispositionKey) + 1, 'Newest')
SET IDENTITY_INSERT EY_CMT_TestV2..CMT_M_DISPOSITION OFF
SET IDENTITY_INSERT EY_CMT_TestV2..CMT_M_DISPOSITION ON
Insert into CMT_M_DISPOSITION(DispositionKey,DispositionValue) select MAX(DispositionKey) + 1, 'Newest' from CMT_M_DISPOSITION
SET IDENTITY_INSERT EY_CMT_TestV2..CMT_M_DISPOSITION OFF
The identity insert allows you to insert explicit values (in this case, the explicit value defined in INSERT INTO ... SELECT) and hence needs to be turned ON before the insert.

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Why am I getting an error doing an insert when IDENTITY_INSERT is set to OFF?
How do I turn it on properly in SQL Server 2008? Is it by using SQL Server Management Studio?
I have run this query:
SET IDENTITY_INSERT Database. dbo. Baskets ON
Then I got the message back in the console that the Command(s) completed successfully.
However when I run the application, it still gives me the error shown below:
Cannot insert explicit value for identity column in table 'Baskets' when
IDENTITY_INSERT is set to OFF.
Via SQL as per MSDN
SET IDENTITY_INSERT sometableWithIdentity ON
INSERT INTO sometableWithIdentity
(IdentityColumn, col2, col3, ...)
VALUES
(AnIdentityValue, col2value, col3value, ...)
SET IDENTITY_INSERT sometableWithIdentity OFF
The complete error message tells you exactly what is wrong...
Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.
I had a problem where it did not allow me to insert it even after setting the IDENTITY_INSERT ON.
The problem was that i did not specify the column names and for some reason it did not like it.
INSERT INTO tbl Values(vals)
So basically do the full INSERT INTO tbl(cols) Values(vals)
Import:
You must write columns in INSERT statement
INSERT INTO TABLE
SELECT * FROM
Is not correct.
Insert into Table(Field1,...)
Select (Field1,...) from TABLE
Is correct
I know this is an older thread but I just bumped into this. If the user is trying to run inserts on the Identity column after some other session Set IDENTITY_INSERT ON, then he is bound to get the above error.
Setting the Identity Insert value and the subsequent Insert DML commands are to be run by the same session.
Here #Beginner was setting Identity Insert ON separately and then running the inserts from his application. That is why he got the below Error:
Cannot insert explicit value for identity column in table 'Baskets' when
IDENTITY_INSERT is set to OFF.
It looks necessary to put a SET IDENTITY_INSERT Database.dbo.Baskets ON; before every SQL INSERT sending batch.
You can send several INSERT ... VALUES ... commands started with one SET IDENTITY_INSERT ... ON; string at the beginning. Just don't put any batch separator between.
I don't know why the SET IDENTITY_INSERT ... ON stops working after the sending block (for ex.: .ExecuteNonQuery() in C#). I had to put SET IDENTITY_INSERT ... ON; again at the beginning of next SQL command string.
This is likely when you have a PRIMARY KEY field and you are inserting a value that is duplicating or you have the INSERT_IDENTITY flag set to on
Another option is where you have tables like 'type' or 'status', for example, OrderStatus, where you always want to control the Id value, create the Id (Primary Key) column without it being an Identity column is the first place.

SQL: Will setting IDENTITY_INSERT ON disable updating the table's identity table?

I'm currently working on a data migration project and for performance-related issues, I want to predefine a set of identities rather than letting the tables generate them.
I found it's not easy to add the identity property to a column, so I want to use IDENTITY_INSERT ON statement.
My question is: would this disable updates to the table's identity table (which is impacting performance), or do I need to truly remove the identity property of the column(s)?
It's very common for data migration scripts to have something like:
SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] ...
INSERT INTO [MyTable] ...
INSERT INTO [MyTable] ...
...
SET IDENTITY_INSERT [MyTable] OFF
While enabled, the field will not auto-increment for other inserts.
IDENTITY_INSERT has session scope, so only your session will be able to insert to the identity row explicitly. AND only one table in a session can have IDENTITY_INSERT ON at a time.
So what about performance? I don't actually have an answer to you question, but I have some code that should give you an answer. It's a modified version of something I found here:
/* Create a table with an identity value */
CREATE TABLE test_table
(
auto_id INT IDENTITY(1, 1),
somedata VARCHAR(50)
)
GO
/* Insert 10 sample rows */
INSERT INTO test_table
SELECT 'x'
GO 10
/* Get the current identity value (10) */
SELECT Ident_current('test_table') AS IdentityValueAfterTenInserts
GO
/* Disable the identity column, insert a row, enable the identity column. */
SET identity_insert test_table ON
INSERT INTO test_table(auto_id, somedata)
SELECT 50, 'x'
SET identity_insert test_table OFF
GO
/* Get the current identity value (50) */
SELECT Ident_current('test_table') AS IdentityValueAfterIdentityInsertWithIdentityEnabled
GO
/* Disable the identity column, insert a row, check the value, then enable the identity column. */
SET identity_insert test_table ON
INSERT INTO test_table(auto_id, somedata)
SELECT 100, 'x'
/*
Get the current identity value (?)
If the value is 50, then the identity column is only recalculated when a call is made to:
SET identity_insert test_table OFF
Else if the value is 100, then the identity column is recalculated constantly and your
performance problems remain.
*/
SELECT Ident_current('test_table') AS IdentityValueAfterIdentityInsertWithIdentityDisabled
SET identity_insert test_table OFF
GO
/* Get the current identity value (100) */
SELECT Ident_current('test_table') AS IdentityValueAfterIdentityInsertWithIdentityEnabled
GO
DROP TABLE test_table
I don't have a SQL SERVER handy to run this on, so let me know how it goes. Hope it helps.
Something to note about Identity columns with SET IDENTITY_INSERT ON.
Just checked on SQL 2012 you can't insert using the built in auto identity if you turn the option on.
Quick test below...
BEGIN TRY DROP TABLE #T END TRY BEGIN CATCH END CATCH;
CREATE TABLE #T (id int IDENTITY, Name varchar(50));
INSERT INTO #T (Name) VALUES ('Darren'); -- built in Identity format
SET IDENTITY_INSERT #T ON;
INSERT INTO #T (id, Name) VALUES (5, 'Jerry'); -- explicit format of identity
INSERT INTO #T (Name) VALUES ('Thomas'); -- TRY to use built in format
SET IDENTITY_INSERT #T OFF;
SELECT * FROM #T;
results with ...
(1 row(s) affected)
(1 row(s) affected)
Msg 545, Level 16, State 1, Line 11
Explicit value must be specified for identity column in table '#T__________________________________________________________________________________________________________________000000C34998' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
(2 row(s) affected)