Bitwise Expressions with Transact-SQL
About Bit Field enumerations:
In C/C++/.net family of programming languages, there are 2 types of enumerations(enums) -
- Simple enums -Sequential or custom.
e.g. Days of a week - 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)
“WHERE ((canview & @mypermissionid)=@mypermissionid)”
WHERE ((canview & @mypermissionid)0)
should be cheaper - compares to 0 not to bunch of bits
hmm. thanks. I’ve never used this syntax for comparison. I should read a bit more.