Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting column constraint on a table (SQL Server)

I have a column that should contain one of values of 2 power n: 2,4,8,16,32 etc. I want to enforce that on table schema level - is there a way to specify such a column constraint?

Thanks!

like image 904
Andrey Avatar asked Jul 02 '26 06:07

Andrey


1 Answers

Shamelessly stealing from this answer you could use bitwise operations to do this pretty efficiently.

ALTER TABLE tablename ADD CONSTRAINT
    ckname CHECK (colName > 0 AND (colName & (colName - 1) =0))
like image 60
Martin Smith Avatar answered Jul 03 '26 20:07

Martin Smith