SQL Server - setting column value based on another column
I have a 3 column Part1
, Part2
and OnePiece
.
Part1
can be assigned [1,2,3,4,5].
Part2
you can assign [1,2,3,4].
OnePiece
it is of type Bit
.
Both Part1
and Part2
cannot have the same value, and also, if Part1
equal to 5, then Part2
cannot have a value.
What I am trying to do is set OnePiece
to 1 and make sure it Part2
doesn't take a value when Part1
= 5.
How can i do this?
I will clarify my request.
The column OnePiece
is a flag and is calculated automatically and is set to 1 if Part1
= 5, and for Part2
it cannot be set to any value if Part1
= 5.
The reason is that Part1
= 5 means it is a one component product, so there is no Part2
and should not allow any other value.
So, that would do two things that I'm guessing; trigger and check limit. Hope I have offered more details.
source to share
I made the column OnePiece
calculated using this formula:
(CONVERT([bit],CASE [Part1] WHEN (5) THEN (1) ELSE (0) END,0))
For restrictions:
ALTER TABLE [AssemblyData]
ADD CONSTRAINT [CHK_AssemblyData]
CHECK (([Part2]<>(5))
AND
([Part2]<>[Part1])
AND
([Part1]<>(5) OR [Part2] IS NULL))
Thanks for every user contributing to the answer to this question.
source to share