Are you trying to run a single query that checks all existing data to see if the constraint is violated? Or are you looking for a query you can use in a stored procedure to perform a check before trying insert/update? I threw a couple of things togethee. Hopefully, they help.
Here is the set up:CREATE TABLE dbo.Subjects ( Path int, DisplayName varchar (50))CREATE TABLE SubjectRelations ( Parent int, Child int)INSERT SubjectsSELECT 1, 'Name1'UNION ALL SELECT 2, 'Name2'UNION ALL SELECT 3, 'Name2' --DuplicateUNION ALL SELECT 4, 'Name4'UNION ALL SELECT 5, 'Name5'UNION ALL SELECT 6, 'Name6'INSERT SubjectRelationsSELECT 1, 2UNION ALL SELECT 1, 3UNION ALL SELECT 4, 5UNION ALL SELECT 4, 6
First here is a query that I think will get all duplicates:SELECT Parent, DisplayName, COUNT(*)FROM SubjectsINNER JOIN SubjectRelationsON Path = ChildGROUP BY Parent, DisplayNameHAVING COUNT(*) > 1
Here is some other queries that might help:DECLARE @Parent INTDECLARE @DisplayName VARCHAR(50)DECLARE @Child INTSET @Parent = 1SET @DisplayName = 'Name2'SET @Child = 2-- Test for Insert: if COUNT is greater than 0, constraint violated.SELECT COUNT(DisplayName)FROM Subjects sINNER JOIN SubjectRelations sr1 ON s.Path = sr1.ChildWHERE sr1.Parent = @Parent AND s.DisplayName = @DisplayName-- Test for Update: if COUNT is greater than 0, constraint violated.SELECT COUNT(DisplayName)FROM Subjects sINNER JOIN SubjectRelations sr1 ON s.Path = sr1.ChildWHERE sr1.Parent = @Parent AND s.DisplayName = @DisplayName AND s.Path <> @Child