Tinyint vs Bit?

前端 未结 16 2060
暖寄归人
暖寄归人 2020-12-13 05:13

I don\'t want to touch-off a religious war here, but there seem to be two schools of thoughts in how to represent boolean values in a database. Some say bit is

相关标签:
16条回答
  • 2020-12-13 05:57

    @Kevin: I believe you can use group by on bit fields (SQL Server 2005):

    declare @t table (
        descr varchar(10),
        myBit1 bit, 
        myBit2 bit
    )
    insert into @t values ('test1', 0, 1)
    insert into @t values ('test2', 1, 0)
    insert into @t values ('test3', 1, 1)
    insert into @t values ('test4', 0, 0)
    
    select myBit1, count(myBit1) from @t group by myBit1
    select myBit2, count(myBit1) from @t group by myBit2
    

    Results:

    myBit1 
    ------ -----------
    0      2
    1      2
    
    myBit2 
    ------ -----------
    0      2
    1      2
    
    0 讨论(0)
  • 2020-12-13 05:57

    TinyInt is my preference. Then, when doing aggregated counts against the field, you don't have to cast it. Also, some front-end languages interpret a Bit differently than others, and using a TinyInt makes validation checks universal for any front-end language.

    0 讨论(0)
  • 2020-12-13 06:01

    Bit...unless you're of the "true / false / file not found" clan

    In case you didn't get the reference...

    And in the case of Linq2SQL, bit works with true/false which makes it easier to program for. There's advantages to both.

    And there's also programming maintenance to consider. What happens if you (or a junior intern programmer) uses a 2, 3, 25, 41, 167, 200 etc? Where is that documented? Bits are self-documenting and pretty universal.

    0 讨论(0)
  • 2020-12-13 06:02

    For MySql users - Why you should not use BIT columns in MySQL

    0 讨论(0)
  • 2020-12-13 06:04

    I use bit because it saves me having to use a check constraint, and because my ORM will automatically convert bit into a nullable boolean (C#), which I very much appreciate once coding.

    0 讨论(0)
  • 2020-12-13 06:08

    I use bits when appropriate. Aside from it being semantically the correct type (semantics count!), multiple bit fields (up to 8) in a single row (on SQL Server, anyway) can be consolidated into a single byte of storage. After the eighth, an additional byte is needed for the next 8, and so on.

    References:

    • SQL 2000
    • SQL 2005
    • SQL 2008
    0 讨论(0)
提交回复
热议问题