Can a sql server table have two identity columns?

前端 未结 9 1843
孤城傲影
孤城傲影 2020-11-27 06:23

I need to have one column as the primary key and another to auto increment an order number field. Is this possible?

EDIT: I think I\'ll just use a composite number a

相关标签:
9条回答
  • 2020-11-27 06:54

    I've just created a code that will allow you inserting two identities on the same table. let me share it with you in case it helps:

    create trigger UpdateSecondTableIdentity
    On TableName For INSERT
    as
    update TableName
    set SecondIdentityColumn = 1000000+@@IDENTITY
    where ForstId = @@IDENTITY;
    

    Thanks,

    0 讨论(0)
  • 2020-11-27 06:59
    CREATE TABLE [dbo].[Foo](
        [FooId] [int] IDENTITY(1,1) NOT NULL,
        [BarId] [int] IDENTITY(1,1) NOT NULL
    )
    

    returns

    Msg 2744, Level 16, State 2, Line 1
    Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
    

    So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).

    Edit: msdn:CREATE TABLE (Transact-SQL) and CREATE TABLE (SQL Server 2000):

    Only one identity column can be created per table.

    0 讨论(0)
  • 2020-11-27 06:59

    A workaround would be to create an INSERT Trigger that increments a counter.

    So I have a table that has one identity col : applicationstatusid. its also the primary key. I want to auto increment another col: applicationnumber

    So this is the trigger I write.

     create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as 
           update [Applicationstatus] 
           set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000) 
           from [Applicationstatus] 
           inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid
    
    0 讨论(0)
  • 2020-11-27 07:01

    The primary key doesn't need to be an identity column.

    You can't have two Identity columns.

    You could get something close to what you want with a trigger...

    0 讨论(0)
  • 2020-11-27 07:06

    in sql server it's not possible to have more than one column as identity.

    0 讨论(0)
  • 2020-11-27 07:07

    Add one identity column and then add a computed column whose formula is the name of the identity column

    Now both will increment at the same time

    0 讨论(0)
提交回复
热议问题