SQL Server 中的位运算与C#枚举位运算的结合

首先来讲讲SQL Server 中的位运算:

在SQL Server ,采用1,2,4,8,16.....等用数字标识的状态字段可以进行累加,对存在的几种状态进行组合,从而可形成各种组合状态 

例如:一条记录该字段原来的数字是,2,如我们想加上4,则可以用

update t_User set iFlag = iFlag | 4  where UserID = 1

(iFlag 为该字段名)

例2:在加上4之后我们想去掉4怎么办呢,可以这样实现

update t_User set iFlag = iFlag ^4 where UserID = 1

这样就又把4从该记录中去掉了.

如果我们想选择所有为2的记录该怎么做呢,可以这样实现

select * from t_User where iFlag &2 = 2

SQL中的位运算不但可以取出各种值,而且我们可以对他对数据进行排序

举例如下,新闻列表中的一个字段标识为

1:置顶

2:不置顶

4:推荐

8:不推荐

该字段的值可以为这4种状态的组合,如果我们根据一定条件想把所有置顶的放在前面该如何做呢

select * from t_News order by iFlag & 1 desc

这样我们就把所有置顶的贴子排在前面,当然这里可以加上一定的Where 条件,在Where  里也可可以加一定的位运算,

关于位运算可以查阅相应的SQL 帮助

下面来讲一讲C#中的枚举位运算

这里我们定义一个枚举

    [Flags]
    enum UserFlag
    {
        a = 1,
        b = 2,
        c = 4,
        d = 8,
        e = 16,
        f = 32
    }

 

在代码里加上如下处理

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            string strSQL = "select * from v_User where iFlag & @iFlag = @iFlag";

            //SqlParameter parm = new SqlParameter("@iFlag",SqlDbType.Int,4);
            //parm.Value = UserFlag.a | UserFlag.b ;
            SqlConnection con = new SqlConnection("server=.;database=Sinvan_TexDB;User Id=sa;pwd=123;");

            SqlCommand comm = new SqlCommand(strSQL, con);

            comm.Parameters.Add("@iFlag", SqlDbType.Int, 4).Value = UserFlag.a | UserFlag.b;

            SqlDataAdapter adp = new SqlDataAdapter(comm);
            DataTable dTable = new DataTable();
            adp.Fill(dTable);


            UserFlag userFlag = (UserFlag)Enum.Parse(typeof(UserFlag), dTable.Rows[0][11].ToString());
           

        }
    }

 

进行处理之后userFlag就是数据库中存在的各种组合

我们同样可对其进行一定的位运算处理

如我们想加上 UserFlag.c 可进行如下操作

userFlag = userFlag | Userflag.c

如想去掉UserFlag.c 可进行如下操作

userFlag = userFlag ^ UserFlag.c

如我们要判断是该标识中是否存在c可进行如下操作

(userFlag & UserFlag.c) == UserFlag.c

是不是与SQL Server 中的操作类似,位运算不管什么语言都是通用的,呵呵

可惜Access 不支持位运算,这也是一个遗憾吧,不过有高人写过一模块,一起提供,没进行过测试,供大家参考

 'Binary and operate
 Public Function BitAnd(ByVal a As Long, ByVal b As Long) As Boolean

     If (a <= 0 Or b <= 0) Then
         BitAnd = False
         Exit Function
     End If
     Dim b1() As Integer, b2() As Integer
     ToBytes a, b1
    ToBytes b, b2
    Dim i As Integer
    For i = 0 To 32
        If b1(i) = b2(i) And b1(i) = 1 Then
            BitAnd = True
            Exit Function
        End If
    Next i
    BitAnd = False
End Function

Private Sub ToBytes(ByVal v As Long, ByRef result() As Integer)

    ReDim result(32) As Integer
    Dim iLoc As Integer
    DecToBin v, result(), iLoc

End Sub

Private Sub DecToBin(ByVal v As Long, ByRef result() As Integer, ByRef iLoc As Integer)
    If v < 2 Then
        result(iLoc) = v
        Exit Sub
    End If
    Dim r As Integer
    r = v Mod 2
    result(iLoc) = r
    iLoc = iLoc + 1
    Dim m As Long
    m = v / 2
    DecToBin m, result, iLoc
End Sub

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章