views:

491

answers:

2

Hi,

There is a column in a database that is of type INT (Sql server).

This int value is used at a bit flag, so I will be AND'ing and OR'ing on it.

I have to pass a parameter into my sproc, and that parameter will represent a specific flag item.

I would normally use an enumeration and pass the int representation to the sproc, but since many different modules will be accessing it it won't be practicial for them all to have my enum definition (if it is changed, it will be a headache to roll it out).

So should I use a 'string' or a magic-number as the parameter value, then in my sproc I will do:

IF(@blah = 'approved')
BEGIN
      // bit banging here
END
A: 

Why not use the old 0 and 1 for the flag? It is widely accepted as a bit switch already and there would be no confusion or misspelling as to what 0 and 1 mean. Unless you are saying that there will be more than 2 flags and that more than 1 flag will have the same ultimate meaning

Victor
yes, it has like 4-5 flags stored in the INT column.
Blankman
i would then use the actual int values. using a string as a flag is just asking for trouble IMO.
Victor
+2  A: 

You could use a string, and a CASE construct:

CREATE PROCEDURE BitBang(@Flag AS VARCHAR(50), @Id AS INT)
AS
BEGIN
  DECLARE @Bit INT

  SET @BIT = CASE @Flag
    WHEN 'approved'   THEN 16
    WHEN 'noapproved' THEN 16
    WHEN 'fooflag'    THEN 8
    WHEN 'nofooflag'  THEN 8
  END

  IF @Bit IS NOT NULL
  BEGIN
    IF LEFT(@Flag, 2) = 'no' 
    BEGIN
      UPDATE TheTable SET BitField = BitField & ~@Bit WHERE Id = @Id
    END
    ELSE
    BEGIN
      UPDATE TheTable SET BitField = BitField | @Bit WHERE Id = @Id
    END
  END
END
Tomalak
what is this doing: IF LEFT(@Flag, 2) = 'no' Just to make sure the person didn't put in a trailing space?
Blankman
I assumed you wanted a way to *un*set a bit, too. One way to express this would be using a "[flag]" vs. "no[flag]" argument. This line checks if the flag should be set or if it should be unset. You could also do it by passing an additional parameter (for example, a BIT).
Tomalak