Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server syntax to create clustered primary key

i want to move a table to a new filegroup. Using the accepted answer as a starting point:

CREATE CLUSTERED INDEX CIX_YourTable
   ON dbo.YourTable(YourClusteringKeyFields)
   WITH DROP_EXISTING
   ON [filegroup_name]

i adapt it to my use:

CREATE CLUSTERED INDEX PK_AuditLog_AuditLogID
   ON dbo.AuditLog(AuditLogID)
   WITH DROP_EXISTING
   ON [TheOtherFileGroup]

gives the error:

Msg 1907, Level 16, State 1, Line 1
Cannot recreate index 'PK_AuditLog_AuditLogID'. The new index definition does not match the constraint being enforced by the existing index.

This is, i assume, because PK_AuditLog_AuditLogID is

  • a clustered index
  • a primary key

So i need the syntax to create a primary key clustered index WITH DROP_EXISTING

like image 636
Ian Boyd Avatar asked Jun 27 '12 14:06

Ian Boyd


People also ask

How do you create a primary key in a clustered index?

On the Table Designer menu, click Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box. In the grid, select Create as Clustered, and choose Yes from the drop-down list to the right of the property.

What is primary key clustered?

A clustered index defines the order in which data is physically stored in a table. Table data can be sorted in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key constraint automatically creates a clustered index on that particular column.

How do I create a multi field primary key?

Select the field or fields that you want to use as the primary key. To select one field, click the row selector for the field you want. To select more than one field to create a composite key, hold down CTRL and then click the row selector for each field.


1 Answers

CREATE UNIQUE CLUSTERED INDEX PK_AuditLog_AuditLogID
   ON dbo.AuditLog(AuditLogID)
   WITH DROP_EXISTING
   ON [TheOtherFileGroup]

The logical primary key constraint is preserved (though tested in 2012)

CREATE TABLE dbo.AuditLog
(
AuditLogID int constraint PK_AuditLog_AuditLogID primary key
)


CREATE UNIQUE CLUSTERED INDEX PK_AuditLog_AuditLogID
   ON dbo.AuditLog(AuditLogID)
   WITH DROP_EXISTING
   ON [Primary]



SELECT CONSTRAINT_TYPE  /*Returns PRIMARY KEY*/
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'PK_AuditLog_AuditLogID'
like image 169
MS. Avatar answered Sep 23 '22 23:09

MS.