我有这张桌子
CREATE TABLE [dbo].[CityMaster](
[CityID] [int] NOT NULL,
[City] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BranchId] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF__CityM__Branc__74444068] DEFAULT ((0)),
[ExternalBranchId] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_CityMaster] PRIMARY KEY CLUSTERED
(
[City] ASC,
[BranchId] ASC
),
CONSTRAINT [uk_citymaster_cityid_branchid] UNIQUE NONCLUSTERED
(
[CityID] ASC,
[BranchId] ASC
)
)
和另一张桌子
CREATE TABLE [dbo].[CustomerMaster](
[ID] [int] NOT NULL,
[CustomerCode] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[CustomerName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[CustomerAddress] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[CustomerPhone] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[CustomerEmailId] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[CustomerPriority] [int] NOT NULL CONSTRAINT [DF_CustomerMaster_CustomerPriority] DEFAULT ((0)),
[CustomerRegisterDate] [datetime] NULL,
[CustomerIsActive] [bit] NULL CONSTRAINT [DF_CustomerMaster_CustomerIsActive] DEFAULT ((1)),
[BranchId] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF__CustomerM__Branc__67DE6983] DEFAULT ((0)),
[CityId] [int] NULL CONSTRAINT [DF_CustomerMaster_CityId] DEFAULT ((0)),
CONSTRAINT [PK_CustomerMaster] PRIMARY KEY CLUSTERED
(
[CustomerCode] ASC,
[BranchId] ASC
)
) ON [PRIMARY]
ALTER TABLE [dbo].[CustomerMaster] WITH CHECK ADD CONSTRAINT [fk_cdCityId_CityId] FOREIGN KEY([CityId], [BranchId])
REFERENCES [dbo].[CityMaster] ([CityID], [BranchId])
ALTER TABLE [dbo].[CustomerMaster] CHECK CONSTRAINT [fk_cdCityId_CityId]
如您所见,. 上有一个外键CityId, BranchId
。我遇到的问题是,如果用户没有输入他的城市(他可以选择不输入,这个字段不是强制性的,那么CityId
它将是空白的,当我尝试在CustomerMaster
表中插入这个值时,我得到这个错误说
INSERT 语句与 FOREIGN KEY 约束“fk_cdCityId_CityId”冲突。冲突发生在数据库“TestDatabase”、表“dbo.CityMaster”中。该语句已终止。
所以,我想知道一种方法来规避这个。我知道是否将唯一或主键列作为外键引用,它不能为空。但是,我设定的时间
on delete set null
呢?在这种情况下,如果该行被删除,CityMaster
它将被设置为null
in CustomerMaster
(我的意思是它的所有引用)。那么,如果可能的话,为什么以及如何null
手动设置此外键中的值?如果这无论如何都不可能,那么规避我描述的情况的最佳方法是什么?