Can a sql server table have two identity columns?

前端 未结 9 1844
孤城傲影
孤城傲影 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 07:12

    You can use Sequence for second column with default value IF you use SQL Server 2012

    --Create the Test schema
    CREATE SCHEMA Test ;
    GO
    
    -- Create a sequence
    CREATE SEQUENCE Test.SORT_ID_seq
        START WITH 1
        INCREMENT BY 1 ;
    GO
    
    -- Create a table
    CREATE TABLE Test.Foo
        (PK_ID int IDENTITY (1,1) PRIMARY KEY,
        SORT_ID int not null  DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
    GO
    
    INSERT INTO Test.Foo VALUES ( DEFAULT )
    INSERT INTO Test.Foo VALUES ( DEFAULT )
    INSERT INTO Test.Foo VALUES ( DEFAULT )
    
    SELECT * FROM Test.Foo 
    
    -- Cleanup
    --DROP TABLE Test.Foo
    --DROP SEQUENCE Test.SORT_ID_seq
    --DROP SCHEMA Test
    

    http://technet.microsoft.com/en-us/library/ff878058.aspx

    0 讨论(0)
  • 2020-11-27 07:16
    create table #tblStudent
    (
        ID int primary key identity(1,1),
        Number UNIQUEIDENTIFIER DEFAULT NEWID(),
        Name nvarchar(50)
    )
    

    Two identity column is not possible but if you accept to use a unique identifier column then this code does the same job as well. And also you need an extra column - Name column- for inserting values.

    Example usage:

    insert into #tblStudent(Name) values('Ali')
    
    select * from #tblStudent
    

    Ps: NewID() function creates a unique value of type uniqueidentifier.

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

    No it is not possible to have more than one identity column.

    The Enterprise Manager does not even allow you to set > 1 column as identity. When a second column is made identity

    Also note that @@identity returns the last identity value for the open connection which would be meaningless if more than one identity column was possible for a table.

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