While the bitwise operator suggested by James will work, it will not be very performant in a relational database, especially when you try to scale to millions of records. The reason is that functions in the where clause are not sargable (they prevent an index seek).
What I would do would be create a table which contains all possible combinations of flags and conditions, which will enable an index seek on the condition.
Populate FlagConditions. I used a single (tinyint). Should you need more Flags, you should be able to expand on this approach:
CREATE TABLE FlagConditions (
Flag TINYINT
, Condition TINYINT
, CONSTRAINT Flag_Condition PRIMARY KEY CLUSTERED (Condition,Flag)
);
CREATE TABLE #Flags (
Flag TINYINT IDENTITY(0,1) PRIMARY KEY CLUSTERED
, DummyColumn BIT NULL);
GO
INSERT #Flags
( DummyColumn )
SELECT NULL;
GO 256
CREATE TABLE #Conditions(Condition TINYINT PRIMARY KEY CLUSTERED);
INSERT #Conditions ( Condition )
VALUES (1),(2),(4),(8),(16),(32),(64),(128);
INSERT FlagConditions ( Flag, Condition )
SELECT
Flag, Flag & Condition
FROM #Flags f
CROSS JOIN #Conditions c
WHERE Flag & Condition <> 0;
DROP TABLE #Flags;
DROP TABLE #Conditions;
Now you can use the FlagConditions table any time you need to efficiently seek on an enum bitwise condition:
DECLARE @UserFlags TABLE (Username varchar(10), Flag tinyint);
INSERT @UserFlags(Username, Flag)
VALUES ('User1',6),('User2',4),('User3',14);
DECLARE @Condition TINYINT = 2;
SELECT u.*
FROM @UserFlags u
INNER JOIN FlagConditions fc ON u.Flag = fc.Flag
WHERE fc.Condition = @Condition;
This returns:
Username Flag
---------- ----
User1 6
User3 14
Your DBA will thank you for going this set oriented route.