SQL: How to toggle a bit field

Here is a very simple yet nifty little function to perform a bit-wise operation in an SQL update statement. The following statement is an example that toggles a bit value for a field named IsLockedOut.

Update aspnet_Membership
Set
IsLockedOut = IsLockedOut ^ 1
Where
UserID=@UserID





6521 views

Feedback is appreciated!



Comments 1-1 of 1
percyF 1/18/2010 12:27:37 AM
The quickest way I've found is to subtract the bit value from 1. Like this.

"UPDATE myTable set myToggleBit = 1 - myToggleBit Where ..."

It works because these bit fields are stored in Sql Server as 0 or 1.

1 - 0 (myTobbleBit) = 1
1 - 1 (myToggleBit) = 0

It's quicker, I suppose that doing an Exclusive Or (^) operation on the bit.

  Live Chat
Live Chat


Advanced CAPTCHA Techniques
5/4/2009 6:55:55 PM
The basic principal of a CAPTCHA is to prevent automated submissions, thus consideration is given only to those deemed to have been submitted by a hum...(read more)

SQL: How to toggle a bit field
4/12/2009 3:40:01 PM
Here is a very simple yet nifty little function to perform a bit-wise operation in an SQL update statement. The following statement is an example that...(read more)

RSS 2.0
RSS 2.0
(941) 580-9130    
© 2008 Sarasota Webs
Site Map Validate XHTML