SQL Bitwise Mask Example


DECLARE @SUN INT, @MON INT, @TUE INT, @WED INT, @THU INT, @FRI INT, @SAT INT
SELECT @SUN = 1,
@MON = 2,
@TUE = 4,
@WED = 8,
@THU = 16,
@FRI = 32,
@SAT = 64

'@DayMask may be stored in the database somewhere

DECLARE @DayMask INT
SELECT @DayMask = @SUN @MON @TUE @FRI
Print 'Day Mask: ' + CAST(@DayMask AS VARCHAR(10))

DECLARE @IsSUN BIT, @IsMON BIT, @IsTUE BIT, @IsWED BIT, @IsTHU BIT, @IsFRI BIT, @IsSAT BIT
SELECT @IsSUN = @DayMask & @SUN,
@IsMON = @DayMask & @MON,
@IsTUE = @DayMask & @TUE,
@IsWED = @DayMask & @WED,
@IsTHU = @DayMask & @THU,
@IsFRI = @DayMask & @FRI,
@IsSAT = @DayMask & @SAT

SELECT @IsSUN AS Sunday,
@IsMON AS Monday,
@IsTUE AS Tuesday,
@IsWED AS Wednesday,
@IsTHU AS Thursday,
@IsFRI AS Friday,
@IsSAT AS Saturday