SQL Server creating a Table with an IDENTITY COLUMN - uniqueness - sql-server

In SQL Server, I have created a Table with an ID column that I have made an IDENTITY COLUMN,
EmployeeID int NOT NULL IDENTITY(100,10) PRIMARY KEY
It is my understanding, when I use the IDENTITY feature, it auto increments the EmployeeID. What I don't know/not sure is:
Is that IDENTITY number created, unique?
Does SQL search the entire column in the table to confirm the number created does not already exist?
Can I override that auto increment number manually?
If I did manually override that number, would the number I enter be checked to make sure it is not a duplicate/existing ID number?
Thanks for any help provided.

Is that IDENTITY number created, unique?
Yes, Identity property is unique
Does SQL search the entire column in the table to confirm the number created does not already exist? \
It need not, what this property does is, just incrementing the old value
Can I override that auto increment number manually?
Yes, you can. You have to use SET IDENTITY_INSERT TABLENAME ON
If I did manually override that number, would the number I enter be checked to make sure it is not a duplicate/existing ID number?
No, that won't be taken care by SQL Server, you will have to ensure you have constraints to take care of this
Below is a simple demo to prove that
create table #temp
(
id int identity(1,1)
)
insert into #temp
default values
go 3
select * from #temp--now id column has 3
set identity_insert #temp on
insert into #temp (id)
values(4)
set identity_insert #temp off
select * from #temp--now id column has 4
insert into #temp
default values
go
select * from #temp--now id column has 5,next value from the last highest
Updating info from comments:
Identity column will allow gaps once you reseed them,also you can't update them

Related

SQL Insert Into cannot insert NULL

I have set some script that inserts data from an XML file into a SQL database. I am getting the following error.
Cannot insert the value NULL into column 'fighterID', table 'MMA Database.dbo.FIGHTERStemp'; column does not allow nulls. INSERT fails.
I have fighterID set as the primary key and will not allow NULLS. My intention is to have it number each row as they are inserted. I found one answer that advises to modify the column properties to be the identifier. However it will not let me adjust the columns properties without dropping and adding the table again.
I can do that - but what is the SQL syntax to set the identity specification settings? Am I going about this the right way?
It's pretty simple, just set the field with datatype INT (integer) and follow it with keyword IDENTITY. You can include the seed and increment values; e.g. start at 1, increment by 1, or just use the keyword IDENTITY for a 1,1 default.
CREATE TABLE MMA (FighterID INT IDENTITY (1,1), FighterInfo VARCHAR(MAX))
While inserting data into Primary key you can check the previous max id value and then increment it to next value before you insert a new row.
In SQL, you need to drop table before altering its specification. You can do this by taking backup into temp table then drop your main table and then re insert data from temp table.

Alter column to be identity

I've already read the following answers about the impossibility to alter a column into identity once has been created as a regular int.
Adding an identity to an existing column
How to Alter a table for Identity Specification is identity SQL Server
How to alter column to identity(1,1)
But the thing is I have a table which has been migrated to a new one where the ID was not declared as identity from the beginning, because the old table which was created with an ID identity a long time ago has missing rows due to a purge of historical data. So as far as I know, if I add a new column as identity on my new table, it will automatically create the column sequentially and I need to preserve the IDs from the old table as-is because there is already data linked to these previous IDs.
How can I do transform my ID column from the new table as identity but not sequentially, but with the IDs from the old table?
You could try this approach:
Insert rows with old ID with SET IDENTITY_INSERT <new table> ON. This allows you to insert your own ID.
Reseed the Identity, setting it to the highest ID value +1 with DBCC CHECKIDENT ('<new table>', RESEED, <max ID + 1>). This will allow your Identity to increase from the highest ID and forward.
Something like this in code:
-- Disable auto increment
SET IDENTITY_INSERT <new table> ON
-- <INSERT STUFF HERE>
SET IDENTITY_INSERT <new table> OFF
-- Reseed Identity from max ID
DECLARE #maxval Int
SET #maxval = ISNULL(
(
SELECT
MAX(<identity column>) + 1
FROM <new table>
), 0)
DBCC CHECKIDENT ('<new table>', RESEED, #maxval)
EDIT: This approach requires your ID-column to be an Identity, of course.
If you don't have nulls in the field that you want to copy over from your previous version, you could first figure out what the largest ID is by just doing a max(Id) select. Then using SSMS go add your new field and when you set it as identity, just set the SEED value to something higher than what your current max is so you don't have collisions on new inserts.
I have a process where a temp table is used between a source file, CSV and the production table. The temp table has to match the CSV file columns, there is no PK in this data.
To find a set of rows before and after where the Azure Data Factory was failing, I imported over 2,000,000 rows into a temp table. The process stopped in Azure at 1,500,000 rows.
The error was that an integer or string would be truncated.
This line of code added a PK to the temp table and incremented it:
ALTER TABLE ##FLATFILETEMPBDI ADD ROWNUM INT IDENTITY
That would be the simplest solution to get a row number. I was then able to do this query to find the rows just before and after 1,500,000:
SELECT
ROWNUM
, PARTDESCRIPTION
, LEN(PARTDESCRIPTION) AS LENDESCR
, QUANTITY
, ONORDER
, PRICE
, MANUFACTURERPARTNUMBER
FROM ##FLATFILETEMPBDI
WHERE ROWNUM BETWEEN 1499990 AND 1500005
Works perfectly -- was not planning on it to be that easy, was surprised as anyone to see that the ALTER TABLE with IDENTITY worked to do the numbering for me.

Some tables id column do not auto increment despite being identity

I am troubleshooting a db (not my forte) that has some tables that are auto incrementing on the id column and some tables are not?
Now all the tables are set as identity and marked to disallow null. I am using SSMS what else can I check or do to get these tables back to auto incrementing?
TIA
Interestingly to me...probably old news to you guys. The issue had to do with existing data. So for example a table that had 100 rows in did NOT have the identity column setup. So I would go in and make it an identity with a seed of 1 incrementing 1. Well the seed was somehow having trouble because there was already 100 rows in there. So for all my tables I had to do a row count and seed the identity from the next row. Now it is working as expected.
Having an IDENTITY column is pretty straightforward for a table, and if you are not seeing the auto incrementing behavior of a column on inserts, then I'd first verify that your column is indeed an IDENTITY column:
use <Your Database Name>;
go
select
name,
is_identity
from sys.columns
where object_id = object_id('<Your Table Name>')
order by column_id;
Substitute <Your Database Nam> and <Your Table Name> for their appropriate values.
The other possibility is that data that "appears" to be non-incrementing could have been pushed out to that with a session that set identity insert and pushed out explicit values.
ALTER TABLE YourTable MODIFY COLUMN YourTable_id int(4) auto_increment

SQL SERVER : Sequential identity value on Insert

I am stuck with this seemingly simple issue.
I have a sql server 2008 table tblCabinet with CabinetID as Primary Key and Identity (Seed=1)
Now i insert into and delete from this table. So now when i enter a new row into tbl insert
Insert into tblCabinet values ('F',5,5,5)
It enters a new row with Cabinet ID of 11. I know it has happened because i have deleted the rows in between .
How do i ensure it takes the next available identity, in this case Cabinet ID of 4 by still keeping identity insert ON ? i know i can enter manually by inserting MAX (CabinetID) +1.
You can reset the seed permanently like this:
declare #max int;
select #max = max(key) from table;
dbcc checkident(table,reseed,#max)
but really there isn't any nice way to do this I know of.
you need to set Primary Key and Identity off and have to calculate it manually.
your insert query will look like
Insert into tblCabinet
values (Select MAX (CabinetID) +1 FROM tblCabinet ,'F',5,5,5)

Composite key in SQL Server

I am using Sql Server with Composite key. In this composite key contains one identity column i.e Auto incrment value. i want to generate in this column with duplicate values. How can i do this. Please give me a solution for this.
Thanks with Regards
Saravanan.M
The identity column cannot(corrected based on feedback from #AlexKuznetsov) should not have duplicates within the column itself - it is generally meant to be a unique column and a provide non-identifying value for each row.
If you are asking how to put values into the identity column that already exist in another column, you have to do the following:
Set IDENTITY_INSERT Schema.TableName ON
Insert Into TableName (PK1, PK2, IdentityCol1, OtherCol1, OtherCol2)
SELECT FirstCol, SecondCol, SecondCol, OtherColumn1, OtherColumn2
FROM SomeOtherTable
Set IDENTITY_INSERT Schema.TableName OFF
note that PK2 and IdentityCol1 both get the same value
It would be good if you could provide more context around what you are wanting to do and why? There are some good reasons to use composite keys, but if you're already using an identity field, why not make that your primary key?
Your auto-incrementing identity column should be left untouched and should continue to uniquely identify your rows. It is generally good practice to always have an abstract identity column as your primary key.
If you have 2 other values in your data model which uniquely identify your row, they should be in 2 other columns. If one of them is an auto-incrementing number then you can generate the value either in a stored proc which is used for all insertions or in an insert trigger.
Although this is not quite an answer, several answerers have made one and the same mistake, claiming that "You cant have an identity column with duplicates". In fact, identities may easily be not unique if you do not enforce their uniqueness by an index or constraint, as follows:
CREATE TABLE identityTest(i INT IDENTITY(1,1));
GO
INSERT identityTest DEFAULT VALUES;
INSERT identityTest DEFAULT VALUES;
SET IDENTITY_INSERT identityTest ON;
INSERT INTO identityTest(i)
SELECT i FROM identityTest;
SET IDENTITY_INSERT identityTest OFF;
SELECT i FROM identityTest;
i
-----------
1
2
1
2
GO
DROP TABLE identityTest;

Resources