Finding identity column in a Table
When trying to run an insert statement I get the following error:
Msg 544, Level 16, State 1, Line 3
Cannot insert explicit value for identity column in table 'IV00101' when IDENTITY_INSERT is set to OFF.
Is there a simple way to find what identity column I am trying to insert into that is causing this error?
Problem is my insert statement has 84 values I am inse开发者_StackOverflow中文版rting into.
I am using Microsoft SQL 2008
SELECT name
FROM sys.columns
WHERE [object_id] = OBJECT_ID('dbo.IV00101')
AND is_identity = 1;
Your question is a bit unclear, but I'll take a stab at it:
It sounds like the identity column is auto-incrementing, and you're trying to insert the value.
You can use this query to get the identity column for all tables:
select TABLE_NAME + '.' + COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
You can query the system objects info to find out which columns are identity
SELECT c.name
FROM
sys.columns c
JOIN sys.objects o ON c.object_id = o.object_id
WHERE
o.name = 'TABLE_NAME' -- replace with table nae
AND c.is_identity = 1
select name
from sys.identity_columns
where [object_id] = object_id('your_table_here')
You are trying to override the default identity, to do that you need to add this at the top of your query
SET IDENTITY_INSERT [ database_name . [ schema_name ] . ] table { ON | OFF }
If your table has a primary key, the identity column will probably be the primary key, as already mentioned in James Johnson's answer.
If it's not, you could just let SQL Server Management Studio create the complete CREATE TABLE
script for the table, and search for the word IDENTITY
inside it.
In my opinion, this is the easiest and fastest way to to this (and sufficient for a one-time action).
EDIT:
@Aaron Bertrand:
I know that primary key and identity are two different concepts.
But, honestly: of all the tables with an identity column that you ever saw, how many did you see where the identity column was not the primary key?
You are saying yourself that this is common practice.
So, what I'm saying is this:
Yes, finding the primary key in SSMS is IMO easier than finding the identity column.
(honestly: I don't know any better way to find the identity column using SSMS, that's why I suggested the way I described above)
--> if finding the primary key also means finding the identity in 95% of all cases, why not try to use the easy/fast way (find the primary key) first?
If the primary key is not the identity column, you can still search for the identity column using the "correct" way from your answer (which is without any doubt the correct way, but not as easy as finding the primary key in the UI).
精彩评论