How To Create Table with Identity Column

前端 未结 4 1772
深忆病人
深忆病人 2020-11-27 17:18

I have an existing table that I am about to blow away because I did not create it with the ID column set to be the table\'s Identity column.

Using

相关标签:
4条回答
  • 2020-11-27 17:42

    Unique key allows max 2 NULL values. Explaination:

    create table teppp
    (
    id int identity(1,1) primary key,
    name varchar(10 )unique,
    addresss varchar(10)
    )
    
    insert into teppp ( name,addresss) values ('','address1')
    insert into teppp ( name,addresss) values ('NULL','address2')
    insert into teppp ( addresss) values ('address3')
    
    select * from teppp
    null string , address1
    NULL,address2
    NULL,address3
    

    If you try inserting same values as below:

    insert into teppp ( name,addresss) values ('','address4')
    insert into teppp ( name,addresss) values ('NULL','address5')
    insert into teppp ( addresss) values ('address6')
    

    Every time you will get error like:

    Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
    The statement has been terminated.

    0 讨论(0)
  • 2020-11-27 17:45

    This has already been answered, but I think the simplest syntax is:

    CREATE TABLE History (
        ID int primary key IDENTITY(1,1) NOT NULL,
        . . .
    

    The more complicated constraint index is useful when you actually want to change the options.

    By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

    0 讨论(0)
  • 2020-11-27 17:49
    CREATE TABLE [dbo].[History](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [RequestID] [int] NOT NULL,
        [EmployeeID] [varchar](50) NOT NULL,
        [DateStamp] [datetime] NOT NULL,
     CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
    ) ON [PRIMARY]
    
    0 讨论(0)
  • 2020-11-27 17:52
    [id] [int] IDENTITY(1,1) NOT NULL,
    

    of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

    enter image description here

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