|
Question : NEGATE BIT
|
|
Hi, i would like to uptade a bit value with it negate actual value, it would look something like this
UPDATE TableName SET column = NOT column WHERE some_expresion
But it fails... I've also tried with ! operator but i fails too... Some sugestion?
P.D: Sorry for my English
|
|
Answer : NEGATE BIT
|
|
BIT is not a logical data type so the NOT operator doesn't work. You might want to think of BIT as a one bit numeric type. Instead code:
UPDATE TableName SET column = CASE WHEN column=1 THEN 0 ELSE 1 END WHERE some_expression
If you're using SQL Server 2000, you can encapsulate the BIT negation in a UDF. Here's the creation script:
CREATE FUNCTION dbo.udf_BitNotBIT (
@BIT bit -- ) RETURNS bit -- 1 if @BIT is 0 and 0 if @BIT is 1 /* * Reverses the value of a BIT. Sort of like a NOT, but T-SQL * doesn't treat BIT as a logical so NOT doesn't work. * * Common Usage: select dbo.udf_BitNotBIT(1, 2) * Test: PRINT 'Test 1 ' + CASE WHEN 0=dbo.udf_BitNotBIT (1) THEN 'Worked' ELSE 'ERROR' END * * © Copyright 2002 Andrew Novick http://www.NovickSoftware.com * You may use this function in any of your SQL Server databases * including databases that you sell, so long as they contain * other unrelated database objects. You may not publish this * UDF either in print or electronically. ***************************************************************/
AS BEGIN
RETURN CASE WHEN @BIT=1 THEN 0 ELSE 1 END
END GO
GRANT EXECUTE ON [dbo].[udf_BitNotBIT] TO PUBLIC GO GO
Then the UPDATE would become:
UPDATE TableName SET column = dbo.udf_BitNotBIT (column) WHERE some_expression
There are more sample UDFs in the T-SQL UDF of the week newsletter archive at: http://www.NovickSoftware.com/UDFofWeek/UDFofWeek.htm
Regards, Andy
|
|
|
|