I Apologize, but I have exposed my question to google_and_ChatGPT. I Think a need a ... human. Is my question so hard ?
To me, yes.
I have two colums in a Table in a SQL Server database.
I have checked that (int)Logicial_Value stays into [0;2] by
Logical_Value BETWEEN 0 AND 2
I need to check if
Int_Value < 5000 WHEN Logical_Value = 0
Int_Value > 9999 WHEN Logical_Value = 2
(Gift : I let you guess what the Logical_Value = 1 should imply)
My Check Constraint Expression is :
CASE
WHEN Logical_Value = 0 THEN Int_Value < 5000
WHEN Logical_Value = 1 THEN Int_Value > 4999 AND Int_Value < 10000
WHEN Logical_Value = 2 THEN Int_Value > 9999
END
The hell, it doesn't work. It just allow any value for Int_Value at each case.
Note that SQL Server Management Studio throws an Error Validating Constraint "foo".
My question is now why it let values (it cannot validate the constraint dear captain) but why it can't validate, and thus, what is the correct syntax ?
I'm feeling I have already RTFM, yes.
CASEdoes not work that way. The syntax isCASE WHEN <boolean expression> THEN <value> ELSE <value> END. Notably, boolean expressions in T-SQL are only allowed in specific contexts and nowhere else (there is no true independent boolean type), so you cannot useCASEto specify a condition here at all (unless you artificially compare to1or0or suchlike). You need to rewrite this usingANDanOR, e.g.(Logical_Value = 0 AND Int_Value < 5000) OR (Logical_Value = 1 AND ...).caseexpression to calculate booleans based on some conditions (other booleans). It is much simpler, logically correct and readable to express this with boolean conditions and operators (and, or, not)caseinstead ofandfor booleans? If you want A and B to be true at the same time, thenA and Bis clear and works the same in every DBMS whilecase when A then B enddoes not. The only possible case may be to apply some conditions that will evaluate to error otherwise (for ex,when data_type = 'int' then value = 5 when data_type = 'date' then value = date '1970-01-01' end)