Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

前端 未结 4 2063
小鲜肉
小鲜肉 2020-12-23 13:00

It is possible to create a primary key or unique index within a SQL Server CREATE TABLE statement. Is it possible to create a non-unique index within a CREA

4条回答
  •  悲&欢浪女
    2020-12-23 13:32

    The accepted answer of how to create an Index inline a Table creation script did not work for me. This did:

    CREATE TABLE [dbo].[TableToBeCreated]
    (
        [Id] BIGINT IDENTITY(1, 1) NOT NULL PRIMARY KEY
        ,[ForeignKeyId] BIGINT NOT NULL
        ,CONSTRAINT [FK_TableToBeCreated_ForeignKeyId_OtherTable_Id] FOREIGN KEY ([ForeignKeyId]) REFERENCES [dbo].[OtherTable]([Id])
        ,INDEX [IX_TableToBeCreated_ForeignKeyId] NONCLUSTERED ([ForeignKeyId])
    )
    

    Remember, Foreign Keys do not create Indexes, so it is good practice to index them as you will more than likely be joining on them.

提交回复
热议问题