Reputation: 4748
Can SQL Server have an identity column based on another column?
I have a table design like this
Audit
AuditId
CompanyId
Everything in the system is audited, and the table can be multi tenant, thus the CompanyId
.
In the context of an audit, people like to see a sequential sequence of events and due to the multi tenant nature, the identity will skip numbers like this.
I would ideally keep AuditId
as a normal identity but wish to have a secondary identity column that is unique to CompanyId
.
Is this possible in SQL Server, or do I need to do it in code?
Upvotes: 1
Views: 109
Reputation: 8545
SQL Server can't have an identity column based on another column because there can be only one identity column in a table.
Upvotes: 1
Reputation: 1667
You could have the companyAuditId populated by an insert trigger. It would be defined as int, but on insert the trigger will
Create trigger trAuditI for insert
UPDATE audit
SET CompanyAuditId = max(companyAuditId)
where companyId
= Inserted.CompanyId
Upvotes: 0