Bitwise calculation to process multiple values in one column with T-SQL



DECLARE @Temp TABLE (ID INT)
INSERT INTO @Temp
SELECT 0 UNION ALL
SELECT 2 UNION ALL
SELECT 4 UNION ALL
SELECT 8 UNION ALL
SELECT 16 UNION ALL
SELECT 28 UNION ALL
SELECT 32 UNION ALL
SELECT 60 UNION ALL
SELECT 62 UNION ALL
SELECT 64 UNION ALL
SELECT 65 UNION ALL
SELECT 80 UNION ALL
SELECT 96 UNION ALL
SELECT 99 UNION ALL
SELECT 112 UNION ALL
SELECT 127  UNION ALL
SELECT 130
 
DECLARE @val INT 

DECLARE 
@Monday bit=1,
@Tuesday bit=0,
@Wednesday bit=0,
@Thursday bit=0,
@Friday bit=0,
@Saturday bit=0,
@Sunday bit=1

--The value comes:
SET @val = 
                       + POWER(2*@Monday,1) 
                       + POWER(2*@Tuesday,2) 
                       + POWER(2*@Wednesday,3)  
                       + POWER(2*@Thursday,4)  
                       + POWER(2*@Friday,5)  
                       + POWER(2*@Saturday,6) 
					   + POWER(2*@Sunday,7)  

					   Print @val

Select
@Monday = 2,
@Tuesday = 4,
@Wednesday = 8,
@Thursday = 16,
@Friday = 32,
@Saturday = 64,
@Sunday = 128




select ID
,Case when 2 & ID =2 Then 1 else 0 End as [Monday]
,Case when 4 & ID =4 Then 1 else 0 End as [Tuseday]
,Case when 8 & ID =8 Then 1 else 0 End as [Wednseday]
,Case when 16 & ID =16 Then 1 else 0 End as [Thurseday]
,Case when 32 & ID =32 Then 1 else 0 End as [Friday]
,Case when 64 & ID =64 Then 1 else 0 End as [Saturday]
, Case when 128 & ID =128 Then 1 else 0 End as [Sunday]

    
From @temp

 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s