Store multiple bit values in a single table column

后端 未结 4 665
有刺的猬
有刺的猬 2020-11-30 14:51

I need to store some sort of day-of-week scheduling in database, where I can schedule a record (say it represents a task) for a day or multiple days of the week. I need to h

4条回答
  •  醉酒成梦
    2020-11-30 14:57

    You are talking about a "bit mask". These are handy devices as you can apply binary math on them to easily check the values, but they do take a little setup. To expand on that a little more it would look something like this.

    -- You will want to work with constants
    DECLARE @Mon INT, @Tue INT, @Wed INT, @Thu INT, @Fri INT, @Sat INT, @Sun INT
    
    SET @Mon = POWER(2,0) -- 1
    SET @Tue = POWER(2,1) -- 2
    SET @Wed = POWER(2,2) -- 4
    SET @Thu = POWER(2,3) -- 8
    SET @Fri = POWER(2,4) -- 16
    SET @Sat = POWER(2,5) -- 32
    SET @Sun = POWER(2,6) -- 64
    
    -- Set Monday and Wednesday
    UPDATE T SET Schedule = @Mon | @Wed
    
    -- Find all tasks scheduled on Tuesday
    SELECT * FROM T WHERE Schedule & @Tue = @Tue
    
    -- Find all tasks scheduled on Tuesday and Saturday
    SELECT * FROM T WHERE Schedule & @Tue | @Sat = @Tue | @Sat
    

提交回复
热议问题