Using SQL Server on Azure: 12.0.2000.8
I've defined the following unique index for TablePrimary
:
CREATE UNIQUE NONCLUSTERED INDEX [IX_TablePrimary_Id]
ON [dbo].[TablePrimary] ([PrimaryId] ASC)
WHERE [PrimaryId] IS NOT NULL
The WHERE
clause allows multiple rows to have NULL
in this column, but every non-NULL value in this column must be unique.
Should the indexed column in TablePrimary
be suitable as the primary key for a foreign key relationship to TableForeign
? Every non-NULL value must be unique and NULL in the foreign table wouldn't create a foreign key relationship anyway. But I am getting an error trying to place the foreign key relationship on TableForeign
.
Unable to create relationship 'FK_TableForeign_TablePrimary'.
There are no primary or candidate keys in the referenced table 'dbo.TablePrimary' that match the referencing column list in the foreign key 'FK_TableForeign_TablePrimary'.
Before I dig deeper into this, I'd like to verify that what I am trying to do is indeed possible. Basically, not every row in TablePrimary
will have children in TableForeign
. But those rows which do exist in TableForeign
must have a matching PrimaryId
in TablePrimary
(there are other ways to get the job done but in this case, I'd need a third table as the cross-ref between TablePrimary
and TableForeign
and I'd like to avoid that if it's not necessary, although, if it is necessary, then it is necessary).