SQL bitwise operator


CREATE PROCEDURE BitwiseOperator (@home bit,  
                                @homeFax bit, 
                                @mobile bit,  
                                @office bit,  
                                @officeFax bit, 
                                @tollfreeOffice bit,  
                                @tollfreeFax bit )
    -- Add the parameters for the stored procedure here

AS
BEGIN
DECLARE @phoneIndicator INT 

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

SET @phoneIndicator = POWER(2*@home,1)  
                    + POWER(2*@homeFax,2) 
                    + POWER(2*@mobile,3) 
                    + POWER(2*@office,4)  
                    + POWER(2*@officeFax,5)  
                    + POWER(2*@tollfreeOffice,6)  
                    + POWER(2*@tollfreeFax,7) 

PRINT @phoneIndicator 

IF ( (2 & @phoneIndicator) = 2 )     PRINT 'Has Home' 
IF ( (4 & @phoneIndicator) = 4 )     PRINT 'Has Home Fax' 
IF ( (8 & @phoneIndicator) = 8 )     PRINT 'Has Mobile' 
IF ( (16 & @phoneIndicator) = 16 )   PRINT 'Has Office' 
IF ( (32 & @phoneIndicator) = 32 )   PRINT 'Has Office Fax' 
IF ( (64 & @phoneIndicator) = 64 )   PRINT 'Has Toll Free Office' 
IF ( (128 & @phoneIndicator) = 128 ) PRINT 'Has Toll Free Fax'

END
GO

Bitwise Operator allows you to do two different values at a binary level and tell you whether the two numbers intersect.

Example:
1 & 0 -- 0 (0000)
1 & 1 -- 1 (0001)
1 & 2 -- 0 (0010)
1 & 3 -- 1 (0011)
1 & 4 -- 0 (0100)
1 & 5 -- 1 (0101)
1 & 6 -- 0 (1010)

8 & 8 -- 8
-- 1000 & 1000 = 1000
8 & 16 -- 0
-- 1000 & 1 0000 = 0

47 & 16 -- 0
--10 1111 & 1 0000 = 0
63 & 16 -- 16
--11 1111 & 1 0000 = 1 0000

16 & 16 -- 16
-- 1 0000 & 1 0000 = 1 0000
17 & 16 -- 16
-- 1 0001 & 1 0000 = 1 0000

#SQL #binary #bitwise operator






你可能感興趣的文章

變數命名的善意

變數命名的善意

Nginx + Flask 動態與靜態頁面分離入門教學

Nginx + Flask 動態與靜態頁面分離入門教學

原型鏈(Prototype Chain)

原型鏈(Prototype Chain)






留言討論