script to add and remove auto-increment property from a column - sql-server

For a sql script I'm working on, I need to programmatically remove the identity, identity seed, and identity increment for a column in an existing table, then add them back to the table at the end of the script. Does anyone have a reference or an example on how to do this?

You should do this:
SET IDENTITY_INSERT <TableName> ON
-- Do the inserting in the table with name <TableName>
SET IDENTITY_INSERT <TableName> OFF
For more details look in the MSDN.

Yes, you just do this:
SET IDENTITY_INSERT [TABLE] ON
And then back on:
SET IDENTITY_INSERT [TABLE] OFF
This will allow you to enter manual data in the identity column.
http://msdn.microsoft.com/en-us/library/ms188059.aspx

Related

When should I use SET IDENTITY_INSERT <tablename> OFF function?

To insert values into the identity column manually, I use:
SET identity_insert product ON
INSERT INTO product (PID, ProdName, Qty, Unitprice)
VALUES (10, 'soap', 5400, 22)
Firstly I have deleted the 10th row/record, then I have used this command to insert the identity value and record it manually.
this command is inserting the record. It's fine
Where should I write the command SET identity_insert product OFF? And what is the use of the SET identity_insert product OFF command?
From the documentation:
At any time, only one table in a session can have the IDENTITY_INSERT property set to ON.
So, if you are in a batch where you want to override the auto-generated identity values on two different tables, you would set the first one to OFF before setting the second one to ON.
(Also, like a lot of things, if you change something from the default, it's never a bad idea to change it back.)
from https://learn.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql?view=sql-server-ver15
At any time, only one table in a session can have the IDENTITY_INSERT
property set to ON. If a table already has this property set to ON,
and a SET IDENTITY_INSERT ON statement is issued for another table,
SQL Server returns an error message that states SET IDENTITY_INSERT is
already ON and reports the table it is set ON for.
so you should set it off before you set it on to another table in your session.

How to SUM to change every row record to a new value?

I am using Microsoft SQL Server Management Studio.
I want to sum each row of my record (say, column ID) with a constant value (say 50).
So here is a better picture:
Click here for the image that i prepared for better understanding of my requirement.
I know SUM can be used to sum up the entire column and come out with a TOTAL at the end of the row, but how about adding every row's record with a constant value?
Once the sum is done, I need to do my last step, which is to reset the ID of the next new row (which doesn't need to SUM like above) from 154 to 999. Can anyone also advice me on resetting primary key?
Dick,
You can change the identity column's next value easily by executing DBCC CheckIdent command
Unfortunately, there is not an easy way to update an identity column value.
For existing records, what I experienced till now is to copy all data into a new temp table and organize values on this helper table. Then drop existing table. As following step rename the temp table to original table name.
If you try to remove identity property of a column, the SSMS generates a script as follows
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_MyTable
(
id int NOT NULL,
value int NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_MyTable SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.MyTable)
EXEC('INSERT INTO dbo.Tmp_MyTable (id, value)
SELECT id, value FROM dbo.MyTable WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.MyTable
GO
EXECUTE sp_rename N'dbo.Tmp_MyTable', N'MyTable', 'OBJECT'
GO
COMMIT
I know this does not sound an easy way to update identity column values.

ALTER COLUMN with INTEGER Datatype, NOT NULL, PRIMARY KEY, auto increment

I have a MySQL QUERY and working fine.
QUERY IS:
ALTER TABLE run
CHANGE RN_RUN_ID RN_RUN_ID INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (RN_RUN_ID);
I tried to execute same Query and modified in MSSQL which is throwing error.
MSSQL QUERY IS:
ALTER TABLE run ALTER COLUMN RN_RUN_ID
RN_RUN_ID INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (RN_RUN_ID);
ERROR IS:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'AUTO_INCREMENT'.
Can you tell me what I did wrong in this query.
You cant do it directly.
See this post: Adding an identity to an existing column
First answer.
In SQL Server there is no such AUTO_INCREMENT option. Please look at the docs. The equivalent is IDENTITY.
You cannot modify a column directly to become IDENTITY. You need to create a new column on the table, or create a new table and rename it. It has some tricky parts (allowing the insert in the identity column, renaming a column, and some other things). Look this SO answer.
There are also differences on the syntax for adding a PK to a table:
ALTER TABLE run
ADD CONSTRAINT PK PRIMARY KEY (rn_run_id)
If you have acces to SQL Server Management Studio you can get the full script easyly:
add a new diagram to the database
add the table to the diagram (rigth click on the window, and use the contextual menu)
save the diagram (you can delete it later)
right click on the table and choose custom view
right click again on the table, and choose "modify custom view". Add the identity, identity initial value, identity increment, key, etc. required elements to the custom view
modify the column properties in the diagram
go to the "Table designer" menu, and choose the last option "Generate change scripts". You'll get an script which does all the changes for you. For example:
An example of doing this process (by modifying the column id of the table test):
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_test
(
id int NOT NULL IDENTITY (10, 2)
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_test SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_test ON
GO
IF EXISTS(SELECT * FROM dbo.test)
EXEC('INSERT INTO dbo.Tmp_test (id)
SELECT id FROM dbo.test WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_test OFF
GO
DROP TABLE dbo.test
GO
EXECUTE sp_rename N'dbo.Tmp_test', N'test', 'OBJECT'
GO
COMMIT
NOTE: the name of the menu options can be different, i don't have an English SSMS at hand right now
Relevant docs:
IDENTITY
DBCC CHECKIDENT
SET IDENTITY_INSERT
ALTER TABLE

Sybase IQ: load table with autoincrement column

I need to transfer a table from database A to database B, the table has an autoincrement column. The content of the table in the new database has to be identical to the table in the original database, including the values in the autoincrement column.
The following LOAD TABLE, where col1 is the autoincrement column, doesn't work:
set identity_insert TableName on;
LOAD TABLE TableName
(col1,col2,col3)
FROM 'file.csv';
I get the following error:
Cannot insert or update Column col1: set option 'identity_insert' to the specific table name containing the identity column to be modified.
Still, I'm setting the identity_insert option. What's wrong with this command?
Please try
SET TEMPORARY OPTION IDENTITY_INSERT = 'MyTable';
This has been discussed on SCN
DEFAULTS OFF looks like it should be used as an option if you want to ovverride the default identity (autoincrement) value.
see: http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00801.1530/doc/html/san1281564935243.html
If that doesn't work, and this is just a one time thing... the simplest way to accomplish this would be to load table into TableName_work that has no autoincrement, then insert the data into your destination via a select statement with identity_insert on.

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

Resources