1

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.

  1. Company1 User logged in
  2. Company1 User logged out
  3. Company1 User logged in
  4. Company9 User logged in
  5. Company1 User logged out
  6. Company9 User logged out

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dale Fraser
  • 4,623
  • 7
  • 39
  • 76

2 Answers2

1

SQL Server can't have an identity column based on another column because there can be only one identity column in a table.

Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
0

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
Mike
  • 1,645
  • 3
  • 13
  • 21