我要创建具有以下约束的表,是否可以使用SQL Server Management Studio?
更新: 我的表创建查询如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductId] [int] NULL,
[CompanyId] [int] NULL,
[Username] [nvarchar](max) NOT NULL,
[Identifier] [nvarchar](max) NULL,
[DeletedAt] [datetime2](7) NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
答案 0 :(得分:1)
您可以使用过滤索引。语法如下:
create unique index unq_thetable_username on the_table(username)
where deleteAt is not null;
我不知道您是否可以通过鼠标点击此解决方案。我只写上面的逻辑。
答案 1 :(得分:1)
您将要使用unique filtered index
。在这里,您可以使用桌子:
/****** Object: Table [dbo].[the_table] Script Date: 7/26/2018 4:04:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[the_table](
[id] [int] NOT NULL,
[productid] [varchar](50) NULL,
[companyid] [varchar](50) NULL,
[username] [varchar](50) NULL,
[identifier] [varchar](50) NULL,
[deleteat] [varchar](50) NULL,
CONSTRAINT [PK_the_table] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
以及用户名的索引:
SET ANSI_PADDING ON
GO
/****** Object: Index [UIDX_USERNAME] Script Date: 7/26/2018 4:03:31 PM ******/
CREATE NONCLUSTERED INDEX [UIDX_USERNAME] ON [dbo].[the_table]
(
[username] ASC
)
WHERE ([DELETEAT] IS NOT NULL)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
另一列将使用相同的索引逻辑,但是我不想通过发布更多来弄乱这个答案!我不会把逻辑放到触发器或存储的proc中弄乱,坏的数据仍然会潜入。如果保持良好的约束,没有人会把数据弄乱:)
答案 2 :(得分:0)
在ProductId和Username上创建唯一索引,并使用where子句将该索引限制为WHERE DeletedAt IS NOT NULL
。 Answer showing an example of a unique filtered index。
您可能还需要AND ProductId IS NOT NULL
子句,尽管该子句不是必需的,但是由于该列为空,因此您应该考虑一下。
与Identifier
类似。
您可能还想考虑一个表的值,在该表中有一行,其中Id
以外的所有列均为空...