Unfortunately, SQL Server won't let you creating a FOREIGN KEY
to a non-unique column.
You can make a trigger which would populate an auxiliary table with unique values of the column, and make a foreign key to that table:
CREATE TABLE
Table1_Y
(
colY VARCHAR(20) NOT NULL PRIMARY KEY,
cnt BIGINT NOT NULL
)
GO
CREATE TRIGGER
TR_Table1_All
ON Table1
AFTER INSERT, UPDATE, DELETE
AS
MERGE
INTO Table1_Y t
USING (
SELECT colY, SUM(cnt)
FROM (
SELECT colY, 1
FROM INSERTED
UNION ALL
SELECT colY, -1
FROM DELETED
) q (colY, cnt)
) s (colY, сте)
ON t.colY = s.colY
WHEN MATCHED AND t.cnt - s.cnt <= 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE
SET t.cnt = t.cnt + s.cnt
WHEN NOT MATCHED BY TARGET AND s.cnt > 0 THEN
INSERT (colY, cnt)
VALUES (s.colY, s.cnt);
GO
then make a foreign key to that table:
ALTER TABLE
Table2
ADD CONSTRAINT
FK_Table2_ColX__Table1_ColY
FOREIGN KEY
(colX)
REFERENCES
Table1 (colY)
GO