Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL create table and index in one query

Is it possible to create indexes(no foreign keys and not unique) and table( not a table variable ) with just one SQL statement like this.

CREATE TABLE tabind
(
    id          int             identity(1,1) primary key   ,
    birthday    datetime        default getdate()           ,
    some_id     int             INDEX index_name, /*this line causes a sql server error*/
    name        nvarchar(100)
);

In fact the equivalent of this statements:

CREATE TABLE tabind
(
    id          int             identity(1,1) primary key   ,
    birthday    datetime        default getdate()           ,
    some_id int             ,
    name        nvarchar(100)
);

create index idx_tabind on tabind(some_id);

My SQL Server Version is 2012.

Thanks.

like image 621
Stefan Michev Avatar asked Oct 03 '14 16:10

Stefan Michev


1 Answers

No, the in-line index declaration is 2014 only.

This actually creates the same index though.

CREATE TABLE tabind
  (
     id       INT IDENTITY(1, 1) PRIMARY KEY,
     birthday DATETIME DEFAULT GETDATE(),
     some_id  INT,
     NAME     NVARCHAR(100),
     CONSTRAINT index_name UNIQUE (NAME, id)
  ); 

SQL Server silently makes non unique non clustered indexes unique by adding in the clustered index key (implicitly created by the PK in your case)

like image 71
Martin Smith Avatar answered Oct 19 '22 12:10

Martin Smith