Naor
Naor

Reputation: 24053

Return a boolean value from a select query

I would like to select boolean value:

SELECT field1, field2, 1 as is_field
FROM TABLE

In Visual Studio 2010 I am doing:

bool b = row.Field<bool>("is_field");

But I get the exception:

Specified cast is not valid.

How can I return a boolean value as boolean and not as int?

Upvotes: 9

Views: 7895

Answers (2)

Ron Klein
Ron Klein

Reputation: 9440

Per @AdaTheDev's suggestion:

bool b = row.Field<int>("is_field") == 1;

Upvotes: 4

AdaTheDev
AdaTheDev

Reputation: 147224

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.

Upvotes: 22

Related Questions