pf » Toggle a Bit with SQL
Toggle a Bit with SQL

I am working on a management dashboard for a client, which uses some AJAX here and there. One simple but really nice feature is that you can enabled or disable things just by clicking on an icon, the state is updated in the background using AJAX (I also add some animation to let the user know that it has been updated).
I wanted to be able to toggle the state of the bit field without a care of the current state. Here's how you can do that in SQL:
UPDATE companies SET active_ind = active_ind ^ 1 WHERE id = ?
I'm using a ^ Bitwise (Exclusive OR or XOR) operator here to do this. To understand what's going on here let's look at a truth table for XOR:
| p | q | p ^ q |
|---|---|---|
| 1 | 1 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 0 | 0 | 0 |
- Dan Dan
SET active_ind = 1 - active_ind
?
Does that work?
1 - 0 = 0 0 - 1 = -1 does this end up as bit 1
1 - 0 = 1
1 - 1 = 0
UPDATE companies SET active_ind = ~active_ind WHERE id = ?
I'll be using this from now on.
I have a similar problem:
I have been banging my head with this one.
Problem:
I have a SQL Query that sets a bit in a field (I didn't write the query)
Code:
UPDATE Table_name SET Options=Options|16 WHERE field='value'
And Also
Code:
UPDATE table_name SET Options=Options|8|4|64|128 WHERE field='value'
I was told this is setting the bit flags in the field and this query does work correctly.
My Question is:
How do I reverse the bit settings? I was told to use the ampersand "&" but it didn't work as I had thought.
So if I set options|16 I can unset options|16
Thanks in advance
--------------------------
so I found the the Tilda "~" (without the quotes) is the reverse binary option, but it didn't do as I thought it would :-(
- Mastering CFQUERYPARAM
- Google Code Search for ColdFusion
- Speaking at CFUNITED 2008
- Getting ColdFusion SQL Statements from SQL Server Trace
- CFSCRIPT Cheatsheet
- 3 New Image Effects for ColdFusion 8
- Googlebot to Submit Web Forms
- ColdFusion 8 Update 1 Fixes some Image Processing Quirks
RSS
add to del.icio.us
Pete Freitag is a software engineer, and web developer located in










