Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update specific bit in integer column

Tags:

I have a mysql table where user permissions are stored as a bitmask:

|user   | permissions | | Admin | 31          | | User  | 13          |             16 8  4  2  1 Admin ->   1  1  1  1  1  -> 16 + 8 + 4 + 2 + 1 -> 31 User  ->   0  1  1  0  1  ->  8 + 4 + 1 -> 13 

Now I want to add a permission for every user with an sql query. Let's say I want to add the permission 16 for everyone without modifying another bit.

 UPDATE users SET permission = ???? 

How do I do this?

like image 758
Jürgen Steinblock Avatar asked Oct 17 '12 06:10

Jürgen Steinblock


People also ask

How do I UPDATE a bit field in SQL?

1 Answer. Show activity on this post. Bits in SQL Server are always stored as 1 or 0 in a bitmap. The "Edit Table" option in SSMS just translates this to True or False for presentation purposes, this is nothing to do with how it is actually stored.

How do I convert bit to int in SQL?

Try using CAST(columnName AS INT) AS IntValue . e.g. OR you can use CONVERT(INT, columnName) AS IntValue .

Which clause is used to limit the rows to be changed in an UPDATE statement?

The LIMIT clause places a limit on the number of rows that can be updated. For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions.


1 Answers

To add permission 16, you just say

UPDATE users SET permission = permission | 16; 

The bitwise OR operator will turn bits on. To turn them off, use a AND operation with the complement of the bit you want off:

UPDATE users SET permission = permission & ~16 
like image 191
Ian Clelland Avatar answered Oct 07 '22 20:10

Ian Clelland