Pergunta

SQL Server 2008 R2

Why

create table A
(
   id int,
   primary key nonclustered (id)
)

is correct and executed without errors?

But

create table A
(
   id int,
   primary key nonclustered id
)

is an error? giving

Incorrect syntax near ')'.

Collateral question:
Why

create table c(id int primary key clustered)  

is executed
but

create table c(id int primary key nonclustered)

is an error? Sorry, both work.

Is it inconsistent syntax to be suggested for correction?

Foi útil?

Solução

The (id) should be in parenthesis. Like CHECK conditions and FOREIGN KEY columns. On one line:

create table A (id int, primary key nonclustered (id)) --ok
create table A (id int, primary key nonclustered id) --not ok

Note: the comma implies "table level constraint". The other syntax without the comma means "column level constraint". Of course PKs are per table, you can have composite keys which can't be defined at the column level:

create table A (
   id int,
   something datetime,

   primary key clustered (id,something)
)

Note: I'd always be explicit about my constraints too for names. Otherwise SQL Server generate a hex looking one. As well as explicitly defining nullability and index style. So I'd write this:

create table A (
   id int NOT NULL,
   something datetime NOT NULL,

   CONSTRAINT PK_A PRIMARY KEY CLUSTERED (id,something)
)

Finally, according to CREATE TABLE, this is OK and works on my SQL Server 2008 instance:

 create table c(id int primary key nonclustered)

Outras dicas

The parentheses are essential because otherwise there would be no way to delimit the PRIMARY KEY column list from whatever follows it (which could be a column or another constraint).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top