我的sql server中有一个现有的表,我想在该表的列上添加一个主键。我知道语法是:
ALTER TABLE PromotionBenefit
ADD CONSTRAINT PK_PromotionBenefit2 PRIMARY KEY CLUSTERED (PromotionBenefitCode);
GO
问题是该列已经有一个主键(相同的约束名称)。所以它抛出一个错误。那样就好。我想知道是否可以在我的查询中添加IF NOT Exists,这样就不会抛出任何错误。
使用什么语法?
编辑:有没有办法使用这种方式:IF NOT EXISTS ....创建PRIMARY KEY CLUSTERED而不是像上面所示改变表? 可以这样做:IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PromotionBenefit]') AND name = N'idx_EventCode')
CREATE NONCLUSTERED INDEX [idx_EventCode] ON [dbo].[PromotionBenefit]
(
[EventCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
GO
答案 0 :(得分:2)
您必须执行以下操作:
DECLARE @IsPrimary INT
SELECT @IsPrimary=COUNT(1)
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'PromotionBenefit'
IF @IsPrimary>0
BEGIN
SELECT 'Table already have Primary Key'
END
ELSE
BEGIN
ALTER TABLE PromotionBenefit
ADD CONSTRAINT PK_PromotionBenefit2 PRIMARY KEY CLUSTERED (PromotionBenefitCode);
GO
END
如果你认为,那就不要比试试这个:
IF NOT EXISTS(
SELECT 1
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'PromotionBenefit')
BEGIN
ALTER TABLE PromotionBenefit
ADD CONSTRAINT PK_PromotionBenefit2 PRIMARY KEY CLUSTERED (PromotionBenefitCode);
GO
END
试试这个:
IF NOT EXISTS(SELECT 1 FROM sys.objects WHERE type = 'PK' AND parent_object_id = OBJECT_ID ('PromotionBenefit'))
BEGIN
ALTER TABLE PromotionBenefit
ADD CONSTRAINT PK_PromotionBenefit2 PRIMARY KEY CLUSTERED (PromotionBenefitCode)
END
希望它对你有所帮助。
答案 1 :(得分:0)
一种做预期的简短方法:
IF OBJECT_ID('idx_EventCode') is null
CREATE NONCLUSTERED INDEX [idx_EventCode] ON [dbo].[PromotionBenefit]
( [EventCode] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,
DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 80) ON [PRIMARY]
GO
OBJECT_ID可与SqlServer中的任何对象一起使用,我还使用它来检测表,视图,存储过程的存在...