patternsqlMinor
Allowing Foreign Key to be Null
Viewed 0 times
allowingnullforeignkey
Problem
I'm trying to create a relationship between two tables where one column in TABLE A is the foreign key for a column in TABLE B. However, there is one row in TABLE B that is currently null in that column and it's giving me an error. However, from Googling the issue, the general consensus seems to be that null is an acceptable value in a foreign key field. But I'm still unable to create this relationship in SSMS due to the error message. How can I bypass this?
Error:
SQL Code as requested:
Thanks
Error:
Unable to create relationship 'FK_RELATIONSHIP'.
The ALTER TABLE statement conflicted with the FOREIGN KEY
constraint "FK_RELATIONSHIP". The conflict occurred in database "DATABASE",
table "TABLE A", column 'COLUMN 1'.SQL Code as requested:
USE [DATABASE]
GO
/****** Object: Table [dbo].[TABLEA] Script Date: 10/02/2012 17:44:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TABLEA](
[COLUMN1] [nvarchar](4) NOT NULL,
CONSTRAINT [PK_TABLEA] PRIMARY KEY CLUSTERED
(
[COLUMN1] 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
/****** Object: Table [dbo].[TABLEB] Script Date: 10/02/2012 17:44:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TABLEB](
[COLUMN1] [nvarchar](15) NOT NULL,
[COLUMN2] [nvarchar](4) NULL,
CONSTRAINT [PK_TABLEB] PRIMARY KEY CLUSTERED
(
[COLUMN1] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GOThanks
Solution
update TABLEA set COLUMN1 = NULL where COLUMN1 = '';
update TABLEB set COLUMN2 = NULL where COLUMN2= '';If you changing your "NULL" values to none and it works, it might just be that there's an empty string or a hidden character in there.
Try recreating your FK after that.
Code Snippets
update TABLEA set COLUMN1 = NULL where COLUMN1 = '';
update TABLEB set COLUMN2 = NULL where COLUMN2= '';Context
StackExchange Database Administrators Q#25323, answer score: 2
Revisions (0)
No revisions yet.