Reverberations

Bitwise Expressions with Transact-SQL

Posted in .net, Coding, SQL by Brajesh on September 3rd, 2006

About Bit Field enumerations:
In C/C++/.net family of programming languages, there are 2 types of enumerations(enums) -

  1. Simple enums -Sequential or custom.
    e.g. Days of a week
  2. Flag enums -Bit field. Bitwise operators give us the ability to store multiple settings in a single primitive data type (e.g. an integer). This is useful when a single item has potentially more than one setting of the same type.
    e.g. bold, underline, italic style of text

Bitwise Operators:
e.g.

public enum textstyle
{
   regular = 0,
   bold = 1,
   italic = 2,
   underline = 4,
   strikethrough = 8
}

If text style is bold and italic I can store text style as
int selectedTextStyle = textstyle.bold + textstyle.italic; //1+2 = 3

Now if I want to check whether selectedTextStyle is bold or not, I’ll just do a bitwise ‘and’ operation, i.e.
bool isBold = ((selectedTextStyle & textstyle.bold) == textstyle.bold);

Here,

selectedTextStyle   3    11
textstyle.bold       1    01
----------------------------
&('and' operation)        01

Bitwise Expressions and Transact-SQL:
Just as any other expression in T-SQL, we can use Bitwise expressions in select, delete, update, insert commands.
e.g.

enum ViewPermissions
{
   None=0;
   student=1;
   teacher=2;
   assistant=4;
}

Here, we should store sum of available view-permissions (2n fields) as integer in a column named ‘canview’ in database. Now all the documents with a particular view-permission can be selected by command such as
SELECT documentid
FROM documents
WHERE ((canview & @mypermissionid)=@mypermissionid)

2 Responses to 'Bitwise Expressions with Transact-SQL'

Subscribe to comments with RSS or TrackBack to 'Bitwise Expressions with Transact-SQL'.

  1. seishin said, on June 4th, 2008 at 8:07 am

    “WHERE ((canview & @mypermissionid)=@mypermissionid)”

    WHERE ((canview & @mypermissionid)0)
    should be cheaper - compares to 0 not to bunch of bits :)

  2. Brajesh said, on June 5th, 2008 at 12:13 pm

    hmm. thanks. I’ve never used this syntax for comparison. I should read a bit more.

Leave a Reply