according to this question, I can't assign the result of a boolean log开发者_运维知识库ic statement into a bit field. My problem is that I am working on a creation script and I have a few dependent flags that require a boolean statement to complete. This script will start as all nulls and the user just enters the data they want to. The script will detect if the record already exists. If so, it will update only the parameters that are not null. If it doesn't exist, the script will create a new record. I am using sql server 2005.
I have the insert statement figured out using ISNULL(@Setting1, 0)
to set a default value when the variable is not assigned. My problem comes with one particular setting which is dependent on 2 of the setting flags. I'd also like to see a solution that could support another setting flag if I needed to add one.
DECLARE @Setting1 bit
DECLARE @Setting2 bit
DECLARE @Setting3 bit
--... code snipped for setting the value
UPDATE
MyTable
SET
EnableSetting1 = ISNULL(@Setting1, EnableSetting1),
EnableSetting1 = ISNULL(@Setting2, EnableSetting2),
EnableSetting1 = ISNULL(@Setting3, EnableSetting3),
EnableComplexSetting1 = ISNULL(@Setting1, EnableComplexSetting1),
EnableComplexSetting2 = ?
WHERE
Id = @MyId
Logically, the ?
would look like ISNULL(@Setting2, EnableSetting2) OR ISNULL(@Setting3, EnableSetting3)
but that is obviously incorrect. How should I set the complex setting 2? How would I do it if logically it was ISNULL(@Setting2, EnableSetting2) OR ISNULL(@Setting3, EnableSetting3) OR ISNULL(@Setting4, EnableSetting4)
, etc?
ISNULL
doesn't return a boolean - it just makes sure to use the second value provided IF the first expression is NULL.
You'll need to use something like this:
UPDATE
MyTable
SET
EnableSetting1 = CASE WHEN @Setting1 IS NULL THEN 1 ELSE 0 END,
...
Depending on which boolean you want to store if @Setting1
is really NULL you might need to switch the two values in the THEN
and ELSE
cases....
With this approach you should be able to also check two conditions:
UPDATE MyTable
SET EnableComplexSetting2 =
CASE WHEN (Complex1 IS NULL AND Complex2 IS NULL) THEN 1 ELSE 0 END
......
精彩评论