Xufeng
Xufeng

Reputation: 6762

How to specify a column to be of bool type

If I want to do something like:

select name, 0 as ischild from people

and specify the ischild column I just made on-the-fly to be a bool column (for later use), how can I do that? Since right now if I read this result set from C# code it always interprets 0 as int, which gives error if I do GetBoolean.

Besides that, if I do something further like:

select * from otherpeople left outer join 
(select *, cast(0 as bit) as ischild from People) q on otherpeople.id = q.id

Now some rows of ischild might be null right? Would should I do if I still want to use GetBoolean on that column?

Upvotes: 0

Views: 87

Answers (4)

Shantanu Gupta
Shantanu Gupta

Reputation: 21198

select name, cast(0 as bit) as ischild from people

Edit

For extended question

Bool has two states -> TRUE or FALSE. However into database you can have TRUE, FALSE OR NULL

If you want to consider NULL as false, then instead of casting in inner query I would prefer casting in outer query

select otherpeople.*, q.*, cast(ISNULL(q.isChild, 0) AS BIT) AS isChild 
from otherpeople left outer join 
(select *, 0 as ischild from People) q on otherpeople.id = q.id

Upvotes: 4

thudbutt
thudbutt

Reputation: 1521

SELECT name, CAST(0 AS BIT) AS ischild FROM people

If you want to include this as part of an outer join where you may potentially get null values then you will need to check for nulls before GetBoolean. You can do this by calling IsDBNull on the column.

See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull(v=vs.110).aspx for an example

if (!reader.IsDBNull(reader.GetOrdinal("ischild")))
               Console.Write(" {0}", reader.GetBoolean(reader.GetOrdinal("ischild")));

Upvotes: 3

Dave Mason
Dave Mason

Reputation: 4936

This should do the trick:

select name, CAST(0 AS BIT) as ischild from people

Upvotes: 0

T McKeown
T McKeown

Reputation: 12857

select name, CAST(0 AS BIT) as ischild from people

Upvotes: 3

Related Questions