1

I have a database table that takes the form of methodID, parentID, headerID and a temporary unique ID for the unique identifier. This table has no foreign keys and the parent ID simply points to another entry in the same table (these are converted to hierarchy IDs later on but that isn't important here).

I have four different types of methods (1-4) and each method must always be a child of the same type of method. For example if method 2 is a child of method 1 every method 2 must then have a method 1 as it's parent.

I need a validation that will select any values that break this rule.

I've been trying to use the following select to make the information sortable:

SELECT *,
    'A method must always have the same type of parent method' 
FROM dr_Allocation_Layer_D_Validation valTable
LEFT JOIN dr_Allocation_Layer_D_Validation DUPE ON DUPE.vd_headerID = valTable.vd_headerID
AND DUPE.vd_temp_uniqueID = valTable.vd_parentID

I have been attempting WHERE clauses in the select to only pick methods the parent method type is not always the same for each method. If anyone can please help me figure this out I would be grateful.

Also I am working in SQL Server 2012. Thanks in advance!

2 Answers 2

1

You can use exists to check if another row with the same methodID and a different parentID exists.

select * , 'A method must always have the same type of parent method' 
from dr_Allocation_Layer_D_Validation t1
where exists (
    select 1 from dr_Allocation_Layer_D_Validation t2
    where t2.vd_methodID = t1.vd_methodID
    and t2.vd_parentID <> t1.vd_parentID
)
1

Use a having condition to select the methods that have more than 1 different parentID. Because all values you need are in the row, you don't need a join to work that out, but you do need a join to neatly display the offending rows.

SELECT DUPE.*
  'A method must always have the same type of parent method' 
FROM (
  select vd_methodID
  from dr_Allocation_Layer_D_Validation
  group by vd_methodID
  having count(distinct vd_parentID) > 1) m
JOIN dr_Allocation_Layer_D_Validation DUPE ON DUPE.vd_methodID = m.vd_methodID
2
  • I actually tried this method and was unable to get it to work. I keep getting the error: Msg 164, Level 15, State 1, Line 7 Each GROUP BY expression must contain at least one column that is not an outer reference. Oct 27, 2014 at 1:50
  • maybe you are using sqlserver? whatever the case, please tag the question with the rdbms you are using. ANyway, Try the latest (more universally usable) edit
    – Bohemian
    Oct 27, 2014 at 2:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.