如何在SQL Server中的外键字段上创建聚簇索引
ALTER TABLE [PERSON_MAIL] ADD
CONSTRAINT [PERSON_MAIL_Person_Id]
FOREIGN KEY CLUSTERED ([Person_Id])
REFERENCES PERSON_KEY(Person_Id)
当我执行上面的查询时,收到错误,例如“关键字'CLUSTERED'附近的语法不正确” 任何人都可以请帮助
答案 0 :(得分: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
答案 1 :(得分: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)