简体   繁体   中英

Define a relationship between two SQL Server tables (parent to child column) without the use of unique or key columns

I am trying to build a table which will hold the 'relationship' of a parent table and a child table. However each column in both tables are no keys or unique and there are duplicate values in each.

Example

Table A - Parent (Fact)

**CartNumber**

Table B - Child

**CartNumber** not unique
CartValue

CartNumber from table A links to CartNumber in B.

I have tried to implement a foreign key with NOCHECK but of course that will not work since the child column is not a primary key or unique. Bear in mind, I am ONLY trying to define that there is a link between the two columns/tables. Is there any way to define a 'loose' relationship between the two columns? Preferably a method where I can reference the sys views or information schema to extract this information

To be honest: This design smells and - if possible - you should think about changing this...

There is no chance to define a FOREIGN KEY CONSTRAINT on non-unique columns the way you describe it.

But: To define a JOIN there is no need for a FK!

My suggestion:

Create a VIEW like this:

CREATE VIEW dbo.MyView
AS
SELECT a.Col1,a.Col2,...
      ,b.Col1,b.Col2,...
FROM TableA AS a
[INNER/LEFT/RIGHT/FULL OUTER] JOIN TableB AS b ON a.RelField=b.RelField;

With such a VIEW you will get the data joined on this non-unique information.

UPDATE

Taken form your comment:

the end goal is just to provide an external web service with information that says Column A from Table A is used to join onto Column B from Table B

You can create a meta-table like this:

CREATE TABLE dbo.ColumnReference
(
 ColumnReferenceID INT IDENTITY
,TABLE_NAME_A VARCHAR(255) NOT NULL
,COLUMN_NAME_A VARCHAR(255) NOT NULL
,TABLE_NAME_B VARCHAR(255) NOT NULL
,COLUMN_NAME_B VARCHAR(255) NOT NULL
);
--inlcude SCHEMA if needed...

In this case you can maintain these relations in your own structure..., you might even add details, rules, what ever...

The web service will call this directly. You might use a VIEW to combine existing relations (defined as FK CONSTRAINT ) with your own meta table (simply with UNION ALL ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM