問題描述
我有一個安全表,其中包含一個組和用戶列表,每個組和用戶都具有按位整數權限.對于每個給定的用戶,我想對他們的所有組和他們的個人權限記錄(如果存在)執行按位 AND.
I have a security table containing a list of groups and users with a bitwise integer permission for each. For each given user, I would like to perform a bitwise AND on all of their groups and of their personal permission record, if present.
當然,我可以在我的代碼中輕松地做到這一點,但我更愿意在數據庫中做到這一點,因為可能有數以千計的項目我正在查詢其權利.
Of course, I can easily do this in my code, but I'd rather do it in the database as there could be thousands of items I am querying the rights for.
相比游標,我更喜歡基于集合的解決方案.
I would prefer a set-based solution over a cursor.
請注意,我無法控制架構.
Note than I do not have control over the schema.
推薦答案
如果您想要按位或單位值的所有值,基于集合的解決方案是可能的:按位求和
A set-based solution is possible if all the values that you want to bitwise or are single-bit values: Performing a bitwise sum
或者,您可以使用不太優雅的方法對非唯一值集進行基于模糊集的按位運算:
Alternatively, you can use a less-elegant method for vaguely-set-based bitwise operations on sets of non-unique values:
DECLARE @BitSum INT
SET @BitSum = 0
SELECT @BitSum = @BitSum | BitValue
FROM (
SELECT 1 AS BitValue
UNION SELECT 7
UNION SELECT 16
) AS SampleValues
SELECT @BitSum
Hugo Kornelis 在另一篇文章中非常全面地回答了這個問題:http://www.eggheadcafe.com/software/aspnet/33139293/b??itwise-aggregate-function.aspx
Hugo Kornelis answers the question pretty comprehensively in this other post: http://www.eggheadcafe.com/software/aspnet/33139293/bitwise-aggregate-function.aspx
這篇關于我可以在 Sql Server 中對一組數字執行按位和嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!