Return a boolean value from a select query

前端 未结 2 1951
误落风尘
误落风尘 2021-01-18 01:51

I would like to select boolean value:

SELECT field1, field2, 1 as is_field
FROM TABLE

In Visual Studio 2010 I am doing:

boo         


        
相关标签:
2条回答
  • 2021-01-18 02:03

    Per @AdaTheDev's suggestion:

    bool b = row.Field<int>("is_field") == 1;
    
    0 讨论(0)
  • 2021-01-18 02:14

    From SQL side, you can do:

    SELECT field1, field2, CAST(1 AS BIT) AS is_field
    FROM TABLE
    

    to force it to be returned as a BIT instead of an int. That should do the trick

    Update: What is your concern for using CAST like this? SQL Server is pretty awesome at optimising e.g. the execution plan for above query would show is_field is a Constant which can be evaluated once up front (there's a related article here: http://msdn.microsoft.com/en-us/library/ms175933.aspx). Even without that, if you're concerned about performance, then you shouldn't worry about it - it would very much be premature optimisation.

    0 讨论(0)
提交回复
热议问题