简体   繁体   English

T-SQL中的位类型

[英]Bit type in T-SQL

In my table, I use the bit type for IsTrue column. 在我的表中,我使用IsTrue列的位类型。

When I execute the select command: 当我执行select命令时:

SqlDataReader reader = command.ExecuteReader(); 

I'm not sure that what would the reader["isTrue"] return ? 我不确定reader["isTrue"]返回什么?

I tried doing the comparison 我尝试进行比较

reader["isTrue"].ToString().Equals("0")

but it didn't work well. 但效果不佳。 Can somebody tell me what I did incorrectly? 有人可以告诉我我做错了什么吗?

It returns a boolean value. 它返回一个布尔值。

bool value = (bool)reader["IsTrue"];

If you know the index of the column in the result set, you can use: 如果您知道结果集中列的索引,则可以使用:

bool value = reader.GetBoolean(index);

I like to do this with extension methods: 我喜欢使用扩展方法来做到这一点:

public static bool ToBool(this string theString)
    {
        bool result = false;
        bool.TryParse(theString, out result);
        return result;

    }

And in your code you can simply do this: 在您的代码中,您只需执行以下操作:

if(reader["isTrue"].ToBool())
{
}

The ToBool extension method will return true/false in the following cases: 在以下情况下,ToBool扩展方法将返回true / false:

  • false if reader["isTrue"] returns DBNull.Value 如果reader [“ isTrue”]返回DBNull.Value,则返回false
  • false if reader["isTrue"] returns 0 (as bit) 如果reader [“ isTrue”]返回0(按位),则返回false
  • true if reader["istrue"] returns 1 (as bit) 如果reader [“ istrue”]返回1(按位),则返回true

And it will never throw an exception when you execute it unless the "isTrue" column is not present in your result set, obviously. 而且,除非您的结果集中没有出现“ isTrue”列,否则它永远不会引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM