我有一个按位枚举,FlagsAttribute就像这样设置 -
[FlagsAttribute]
public enum MyEnum
{
None = 0,
First = 1,
Second = 2,
Third = 4,
Five = 8,
Six = 16,
Seven = 32,
Eight = 64,
Nine = 128
}
现在,在C#中,我将此值存储在属性中,例如MyProperty,在保存时,我在整数列的SQL数据库中写入此属性。假设我从代码中选择First,Second,Five
,然后在数据库中将其保存为'11'
。
我知道我可以从DB获取值,只需要将值转换为MyEnum,它就会给我值。但是,我希望在一些存储过程中对SQL数据进行一些操作,显然我不能将它转换为Enum值。那么,有没有办法可以让我了解个人价值观。
在示例中,如果存储了11,我可以将其作为"1+2+8"
答案 0 :(得分:11)
这可能有助于您入门:
Select 11 & 1 As 'First'
, 11 & 2 As 'Second'
, 11 & 4 As 'Third'
, 11 & 8 As 'Five'
, 11 & 16 As 'Six'
, 11 & 32 As 'Seven'
, 11 & 64 As 'Eight'
, 11 & 128 As 'Nine';
11
是您的储值。
这将为设置的每个值返回非零值(即Select 11 & 1 As 'First'
返回1
,Select 11 & 2 As 'Second'
返回2,Select 11 & 4 As 'Third'
返回0
并且等等。
答案 1 :(得分:6)
您可以执行bitwise operations in SQL
Select *
From MyTable
Where MyEnum = (1 | 2 | 8)
返回设置了哪些标志
Select Case when (MyEnum & 1) = 1 Then 1 else 0 End as First,
Case when (MyEnum & 2) = 2 Then 1 else 0 End as Second,
Case when (MyEnum & 4) = 4 Then 1 else 0 End as Third,
Case when (MyEnum & 8) = 8 Then 1 else 0 End as Fourth,
Case when (MyEnum & 16) = 16 Then 1 else 0 End as Fifth
From MyTable
答案 2 :(得分:0)
declare @MyEnum as Int
set @MyEnum = 11
select
case when ( @MyEnum & 1 ) = 1 then '1+' else '' end +
case when ( @MyEnum & 2 ) = 2 then '2+' else '' end +
case when ( @MyEnum & 4 ) = 4 then '4+' else '' end +
case when ( @MyEnum & 8 ) = 8 then '8+' else '' end
as Bitses
(可能的)尾随加号留给读者练习。
答案 3 :(得分:0)
ID Name
1 Zero
2 One
4 Two
8 Three
16 Four
32 Five
26(或11010)的值对应于One + Three + Four 要获得相关描述,您可以使用下一个请求
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ' | ', '') + Name
FROM [Play].[dbo].[Enums]
where (26 & ID)=ID
Select @Names;
它会为您提供下一个结果One | Three | Four
如果你想得到ids
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + STR(ID)
FROM [Play].[dbo].[Enums]
where (26 & ID)=ID
Select @Names;