2014-11-24 73 views
0

如何在SQL Server上的外鍵字段創建聚集索引如何Foriegn重點-SQL Server上創建聚集索引

ALTER TABLE [PERSON_MAIL] ADD 
    CONSTRAINT [PERSON_MAIL_Person_Id] 
    FOREIGN KEY CLUSTERED ([Person_Id]) 
    REFERENCES PERSON_KEY(Person_Id) 

當我執行上面的查詢,得到錯誤像「關鍵字附近有語法錯誤「 CLUSTERED'「 任何人都可以請求幫助

回答

1

在創建主鍵時,您可以選擇使由sql server創建的索引成爲羣集或非羣集。

在創建外鍵時,sql server不會創建索引,因此沒有索引類型的選項。

您需要分別創建外鍵和索引。

alter table foo 
add constraint fk_bar(bar_id) foreign key 
references bar(id) 
go 

create clustered index ix_foo__bar_id 
on foo(bar_id) 
go 
+0

我將測試它讓你知道輸出 – vmb 2014-11-24 09:03:17

+0

其working.whatü指出的是正確的 – vmb 2014-12-01 12:55:36

0

這裏是解決辦法,如果你沒有在主鍵PERSON_KEY:

CREATE CLUSTERED INDEX Idx_Person 
    ON PERSON_KEY (Person_Id); 


BEGIN TRANSACTION 
SET QUOTED_IDENTIFIER ON 
SET ARITHABORT ON 
SET NUMERIC_ROUNDABORT OFF 
SET CONCAT_NULL_YIELDS_NULL ON 
SET ANSI_NULLS ON 
SET ANSI_PADDING ON 
SET ANSI_WARNINGS ON 
COMMIT 
BEGIN TRANSACTION 
GO 
CREATE TABLE dbo.Tmp_PERSON_KEY 
    (
    Person_Id int NOT NULL 
    ) ON [PRIMARY] 
GO 
ALTER TABLE dbo.Tmp_PERSON_KEY SET (LOCK_ESCALATION = TABLE) 
GO 
IF EXISTS(SELECT * FROM dbo.PERSON_KEY) 
    EXEC('INSERT INTO dbo.Tmp_PERSON_KEY (Person_Id) 
     SELECT Person_Id FROM dbo.PERSON_KEY WITH (HOLDLOCK TABLOCKX)') 
GO 
DROP TABLE dbo.PERSON_KEY 
GO 
EXECUTE sp_rename N'dbo.Tmp_PERSON_KEY', N'PERSON_KEY', 'OBJECT' 
GO 
ALTER TABLE dbo.PERSON_KEY ADD CONSTRAINT 
    PK_PERSON_KEY PRIMARY KEY NONCLUSTERED 
    (
    Person_Id 
    ) WITH(STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 

GO 
CREATE CLUSTERED INDEX Idx_Person ON dbo.PERSON_KEY 
    (
    Person_Id 
    ) WITH(STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
GO 
COMMIT 


    ALTER TABLE [PERSON_MAIL] ADD 
    CONSTRAINT [PERSON_MAIL_Person_Id] 
    FOREIGN KEY ([Person_Id]) 
    REFERENCES PERSON_KEY(Person_Id)