what is the default setting for identity_insert in sql database? - sql

I've had to import some data into a db using IDENTITY_INSERT ON, do I set it back to OFF after the import? what is it's default setting? Obviously I need the application to add records/rows to the tables making a new ID each time.

Default setting depends on how you defined the identity column when you created the table
for example
CREATE TABLE Table_Name(ID INT IDENTITY(1,1))
GO
this ID column will have a Seed value of 1 and increment by 1.
By default you cannot add values to Identity column but you can change this default behaviour by executing the following statement.
SET IDENTITY_INSERT Table_Name ON;
Once you have inserted the values then you can set it back to its default behaviour by executing the following statement.
SET IDENTITY_INSERT Table_Name OFF;
even though we can pass values to Identity column but its not a good practice, since it is an auto generated number, if you add the values into identity column yourself and then Identity column generates the same number later on you can have duplicates in your identity column.
so its best to leave identity column alone, and let it generate the values for you.
if it is necessary to add values to Identity column then I would recommend executing the following statement after every you have Indet_Insert ON and add some values to Identity column,
DBCC CHECKIDENT ( table_name, RESEED, 0)
DBCC CHECKIDENT ( table_name, RESEED)
The 1st statement will RESEED the value of Identity column to the smallest values in your identity column,
2nd RESEED statement with out any Seed value provided, will reseed the Identity value to the next available value to the highest value in your identity column.

In case of someone searching for a way to create a key without identity column:
CREATE TABLE [dbo].[TableName](
[Id] [int] NOT NULL PRIMARY KEY
)
instead of
CREATE TABLE [dbo].[TableName](
[Id] [int] IDENTITY(1,1) NOT NULL
)

Related

Start identity in an existing table / column from a particular number

I have an existing table with thousands of records, with primary key, foreign key and relationships. I have to set the primary key column to be identity, but I don't want to start it from 0 because the table has existing records, and I also don't want to lose data.
I must to save the exact table design.
I have to add an identity, and reseed it.
What should I do?
Thank you!
Just update table with IDs. Then Choose current max ID to execute
DBCC CHECKIDENT ('MyTable', RESEED, maxId)
More about reseeding
You cannot add identity to existing table. Identity has to be specified as part of table creation. You have two options.
Recreate new table with identity properly set up with reseed value & Set up IDENTITY_INSERT ON & Insert existing rows to new table & IDENTITY_INSERT OFF.
CREATE TABLE [dbo].[NewTable](
[ID] [int] IDENTITY(1000,1) NOT NULL PRIMARY KEY, -- 1000 is Reseed value
Col1
Col2
);
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT dbo.NewTable ON;
GO
INSERT INTO NewTable(Id,col1,col2...)
SELECT Id, col1, col2... FROM oldtable;
GO
SET IDENTITY_INSERT dbo.NewTable OFF;
GO
Create a sequence with starting value as the reseed value and use the sequence for your future insertions.
CREATE SEQUENCE dbo.TestSeq
START WITH 1000 -- Reseed value
INCREMENT BY 1 ;
GO
INSERT Test.TestTable (ID, Col1, Col2,...)
VALUES (NEXT VALUE FOR dbo.TestSeq, 1, 2,...) ;
GO
I found the solution:
At SSMS -> Tools -> Options -> Designers: Remove the V from 'Prevent Saving changes that require table re-creation'.
Open the table in Design Mode, and add the V to the Identity Spcification property.
This will also reseed it automatically.

Insert into column without having IDENTITY

I have a table
CREATE TABLE [misc]
(
[misc_id] [int] NOT NULL,
[misc_group] [nvarchar](255) NOT NULL,
[misc_desc] [nvarchar](255) NOT NULL
)
where misc_id [int] not null should have been IDENTITY (1,1) but is not and now I'm having issues
With a simple form that insert into this table but since misc_id is looking for a number that a user would not know unless they have access to the database.
I know a option would be to create another column make it IDENTITY(1,1) and copy that data.
Is there another way I will be able to get around this?
INSERT INTO misc (misc_group, misc_desc)
VALUES ('#misc_group#', '#misc_desc#')
I have SQL Server 2012
You should re-create your table with the desired identity column. The following statements will get you close. SQL Server will automatically adjust the table's identity field to MAX(misc_id) + 1 as you're migrating data.
You'll obviously need to stop trying to insert misc_id with new records. You'll want to retrieve the SCOPE_IDENTITY() column after inserting records.
-- Note: I'd recommend having SSMS generate your base create statement so you know you didn't miss anything. You'll have to export the indexes and foreign keys as well. Add them after populating data to improve performance and reduce fragmentation.
CREATE TABLE [misc_new]
(
[misc_id] [int] NOT NULL IDENTITY(1,1),
[misc_group] [nvarchar](255) NOT NULL,
[misc_desc] [nvarchar](255) NOT NULL
-- Todo: Don't forget primary key but can be added later (not recommended).
)
GO
SET IDENTITY_INSERT misc_new ON;
INSERT INTO misc_new
(
[misc_id],
[misc_group],
[misc_desc]
)
SELECT
[misc_id],
[misc_group],
[misc_desc]
FROM misc
ORDER BY misc_id;
SET IDENTITY_INSERT misc_new OFF;
GO
EXEC sp_rename 'misc', 'misc_old';
EXEC sp_rename 'misc_new', 'misc';
GO
If altering the table is not an option, you can try having a different table with the latest [misc_id] value inserted, so whenever you insert a new record into the table, you retrieve this value, add 1, and use it as your new Id. Just don't forget to update the table after.
Changing a int column to an identity can cause problems because by default you cannot insert a value into an identity column without use the set identity_insert command on. So if you have existing code that inserts a value into the identity column it will fail. However its much easier to allow SQL Server to insert values(that is change it to an identity column) so I would change misc_id into an identity column and make sure that there are no programs inserting values into misc_id.
In MSSQL 2012 you can use SEQUENCE objects:
CREATE SEQUENCE [dbo].[TestSequence]
AS [BIGINT]
START WITH 1
INCREMENT BY 1
GO
Change 1 in START WITH 1 with MAX value for [misc_id] + 1.
Usage:
INSERT INTO misc (misc_id, misc_group, misc_desc)
VALUES (NEXT VALUE FOR TestSequence, '#misc_group#','#misc_desc#')

Trigger for insert on identity column

I have a table A with an Identity Column which is the primary key.
The primary key is at the same time a foreign key that points towards another table B.
I am trying to build an insert trigger that inserts into Table B the identity column that is about to be created in table A and another custom value for example '1'.
I tried using ##Identity but I keep getting a foreign key conflict. Thanks for your help.
create TRIGGER dbo.tr ON dbo.TableA FOR INSERT
AS
SET NOCOUNT ON
begin
insert into TableB
select ##identity, 1;
end
alexolb answered the question himself in the comments above. Another alternative is to use the IDENT_CURRENT function instead of selecting from the table. The drawback of this approach is that it always starts your number one higher than the seed, but that is easily remedied by setting the seed one unit lower. I think it feels better to use a function than a subquery.
For example:
CREATE TABLE [tbl_TiggeredTable](
[id] [int] identity(0,1) NOT NULL,
[other] [varchar](max)
)
CREATE TRIGGER [trgMyTrigger]
ON [tbl_TriggeredTable]
INSTEAD OF INSERT,UPDATE,DELETE
SET identity_insert tbl_TriggeredTable ON
INSERT INTO tbl_TriggeredTable (
[id],
[other]
)
SELECT
-- The identity column will have a zero in the insert table when
-- it has not been populated yet, so we need to figure it out manually
case i.[id]
when 0 then IDENT_CURRENT('tbl_TriggeredTable') + IDENT_INCR('tbl_TriggeredTable')
ELSE i.[id]
END,
i.[other],
FROM inserted i
SET identity_insert tbl_TriggeredTable OFF
END

How to change programmatically non-identity column to identity one?

I have a table with column ID that is identity one. Next I create new non-identity column new_ID and update it with values from ID column + 1. Like this:
new_ID = ID + 1
Next I drop ID column and rename new_ID to name 'ID'.
And how to set Identity on this new column 'ID'?
I would like to do this programmatically!
As far as I know, you have to create a temporary table with the ID field created as IDENTITY, then copy all the data from the original table. Finally, you drop the original table and rename the temporary one. This is an example with a table (named TestTable) that contains only one field, called ID (integer, non IDENTITY):
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_TestTable
(
ID int NOT NULL IDENTITY (1, 1)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_TestTable ON
GO
IF EXISTS(SELECT * FROM dbo.TestTable)
EXEC('INSERT INTO dbo.Tmp_TestTable (ID)
SELECT ID FROM dbo.TestTable WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_TestTable OFF
GO
DROP TABLE dbo.TestTable
GO
EXECUTE sp_rename N'dbo.Tmp_TestTable', N'TestTable', 'OBJECT'
GO
COMMIT
Looks like SQL Mobile supports altering a columns identity but on SQL Server 2005 didn't like the example from BOL.
So your options are to create a new temporary table with the identity column, then turn Identity Insert on:
Create Table Tmp_MyTable ( Id int identity....)
SET IDENTITY_INSERT dbo.Tmp_Category ON
INSERT Into Tmp_MyTable (...)
Select From MyTable ....
Drop Table myTable
EXECUTE sp_rename N'dbo.Tmp_MyTable', N'MyTable', 'OBJECT'
Additionally you can try and add the column as an identity column in the first place and then turn identity insert on. Then drop the original column. But I am not sure if this will work.
Guessing you didn't have much luck with your task....
In table design, you should be able to go into properties and under Identity Specification change (Is Identity) to Yes and assign the column primary key if it formerly had the primary key.
From SqlServerCentral.com
Changing from Non-IDENTITY to IDENTITY and vice versa
An Identity is a property that is set at the time the table is created or a new column is added in alter table statement. You can't alter the column and set it to identity and it is impossible to have two identity columns within the same table.
Depending on the size of the table, is it possible to simply create a new table? copy over the schema of the old one and then use SET IDENTITY_INSERT ON to populate the new identity column with what you want from the old one.

Can a sql server table have two identity columns?

I need to have one column as the primary key and another to auto increment an order number field. Is this possible?
EDIT: I think I'll just use a composite number as the order number. Thanks anyways.
CREATE TABLE [dbo].[Foo](
[FooId] [int] IDENTITY(1,1) NOT NULL,
[BarId] [int] IDENTITY(1,1) NOT NULL
)
returns
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).
Edit: msdn:CREATE TABLE (Transact-SQL) and CREATE TABLE (SQL Server 2000):
Only one identity column can be created per table.
You can use Sequence for second column with default value IF you use SQL Server 2012
--Create the Test schema
CREATE SCHEMA Test ;
GO
-- Create a sequence
CREATE SEQUENCE Test.SORT_ID_seq
START WITH 1
INCREMENT BY 1 ;
GO
-- Create a table
CREATE TABLE Test.Foo
(PK_ID int IDENTITY (1,1) PRIMARY KEY,
SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
GO
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
SELECT * FROM Test.Foo
-- Cleanup
--DROP TABLE Test.Foo
--DROP SEQUENCE Test.SORT_ID_seq
--DROP SCHEMA Test
http://technet.microsoft.com/en-us/library/ff878058.aspx
Add one identity column and then add a computed column whose formula is the name of the identity column
Now both will increment at the same time
No it is not possible to have more than one identity column.
The Enterprise Manager does not even allow you to set > 1 column as identity. When a second column is made identity
Also note that ##identity returns the last identity value for the open connection which would be meaningless if more than one identity column was possible for a table.
create table #tblStudent
(
ID int primary key identity(1,1),
Number UNIQUEIDENTIFIER DEFAULT NEWID(),
Name nvarchar(50)
)
Two identity column is not possible but if you accept to use a unique identifier column then this code does the same job as well. And also you need an extra column - Name column- for inserting values.
Example usage:
insert into #tblStudent(Name) values('Ali')
select * from #tblStudent
Ps: NewID() function creates a unique value of type uniqueidentifier.
The primary key doesn't need to be an identity column.
You can't have two Identity columns.
You could get something close to what you want with a trigger...
in sql server it's not possible to have more than one column as identity.
I've just created a code that will allow you inserting two identities on the same table. let me share it with you in case it helps:
create trigger UpdateSecondTableIdentity
On TableName For INSERT
as
update TableName
set SecondIdentityColumn = 1000000+##IDENTITY
where ForstId = ##IDENTITY;
Thanks,
A workaround would be to create an INSERT Trigger that increments a counter.
So I have a table that has one identity col : applicationstatusid. its also the primary key.
I want to auto increment another col: applicationnumber
So this is the trigger I write.
create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as
update [Applicationstatus]
set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000)
from [Applicationstatus]
inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid