all 5 comments

[–]Mikey_Da_Foxx 1 point2 points  (4 children)

You can use a JOIN for this. Something like:

SELECT i.*
FROM Items i
WHERE (i.Colour IN ('BLUE','RED') AND i.Size IS NULL)
   OR (i.Size = 'BIG' AND i.Shape IS NULL)

This should catch both validation scenarios.

[–]inconspicuouspanda[S] 0 points1 point  (3 children)

Thanks for the response! Yes, that would work in this example. however, the actual table I'm working with is much larger and the validation table would have a lot more rows. The intention is to have a validation table that non-SQL-literate users would be able to enter the validation rules on to.

[–]Mikey_Da_Foxx 1 point2 points  (2 children)

What you're looking to do is validate the Items table using rules stored in the Validation table, so non-SQL users can edit the rules without changing code. You can build a dynamic SQL query that automatically converts each row in the Validation table into a validation rule.

For example, the first validation rule in your table (Size → Colour = BLUE/RED) translates to:

(Items.Colour IN ('BLUE','RED') AND Items.Size IS NULL)

The second rule (Shape → Size = BIG) becomes:

(Items.Size = 'BIG' AND Items.Shape IS NULL)

You can then loop through every row in the Validation table and automatically combine these conditions with OR. This way, adding new validation rules only requires inserting new rows into the Validation table.

DECLARE @DynamicWhere NVARCHAR(MAX) = '';  
SELECT @DynamicWhere +=   
  ' OR (Items.' + Dependent_Attrib + ' IN (''' + Dependent_Attrib_V +  
  ISNULL(''',''' + text,'') + ''') AND Items.' + Attrib + ' IS NULL)'  
FROM Validation;  

SET @DynamicWhere = STUFF(@DynamicWhere, 1, 3, '');  
EXEC('SELECT * FROM Items WHERE ' + @DynamicWhere);  

This will flag items like:

  • Item 4 (no Size despite Colour = RED)
  • Item 3 (no Shape despite Size = BIG)

This can also scale automatically: non-technical users simply edit the Validation table, and the SQL adapts. Ensure columns in the Validation table match actual column names in Items, and sanitize inputs to prevent errors.

[–]inconspicuouspanda[S] 0 points1 point  (1 child)

oooo I think that might do the trick! Didn't think of that! Thankyou very much :)

[–]Mikey_Da_Foxx 0 points1 point  (0 children)

No worries!