Technical Article

Design Errors : PK's with multiple columns on table with identity

,

Run the code.

If there are results, script out the tables and have a look at the identity and the PK structure

If the PK contains the identity column and has extra columns, considering that an identity should be unique, consider altering the table to recreate the PK only on the identity.

There may have been a misunderstanding and there may have been a need to create a unique constraint on the extra columns.

Anyway, ask the devs what the intent was and always test before pressing F5.

-------------------------------------------------------------------------------------------------
-- Purpose: Gets tables that have an Identity together with a PrimaryKey with multiple columns
-- Reasoning: Generally, we expect a Primary Key on the Identity Column only, and if the table is clustered on the PK, this will fatten up the clustered index so fattening up all Indexes,
-- as well as introduce a column into the Clustered index which may undergo change, hence increasing the number of objects needing to be updated if an update occurs on that column.
-- Additionally, You could do identity insert and accidentally insert duplicate ID's into a table where the PK is ill-defined.
-- Author : Doran Mackay
--compatibility : should work on 2005+
-------------------------------------------------------------------------------------------------

select S.name+'.'+o.name TableName,I.Name IndexName,count(*) NumberOfColumnsInPrimaryKey
from sys.indexes I
inner join sys.index_columns INC on I.object_id = INC.object_id and I.index_id = INC.index_id
inner join sys.objects O on O.object_id = I.object_id
inner join sys.schemas S on o.schema_id = s.schema_id
inner join sys.identity_columns IC on i.object_id = IC.object_id
where is_primary_key = 1 and I.index_id = 1
group by S.name+'.'+o.name,I.Name
having count(*) >1

Rate

2.2 (5)

You rated this post out of 5. Change rating

Share

Share

Rate

2.2 (5)

You rated this post out of 5. Change rating