Search code examples
sql-serverbinarylogical-operatorslogical-or

How can I apply a logical OR to a BINARY column so the result is all the correct values?


I have a set of results that are stored in a binary(12) column. I'm looking for all the flags that have been set at various times for a particular condition. It goes something like

Status Flags
1234 0x000000000000000000002000
5678 0x000000000000000000000000
1234 0x000000000000000000000040

What I would like to do is write a query such as

SELECT Status, OR(Flags)
FROM StatusTable
GROUP BY Status

giving the result

Status OR(Flags)
1234 0x000000000000000000002040
5678 0x000000000000000000000000

I can find examples that let me manually OR two values but nothing that applies an OR to a result column. I've greatly simplified the example but we're talking thousands of values with thousands of statuses (mostly 0x000000000000000000000000) making it impractical to manually OR them. I suppose a function could be used and a cursor to loop each one but surely there's an out of the box solution to this?


Solution

  • Writing this in TSQL would be hard, if you can not fix the underlaying design, you can write a .Net CLR User-Defined Aggregate.

    In C# you have binary OR operator: Bitwise and shift operators.
    You can follow this guide to write a CLR function:CLR User-Defined Aggregates