Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 casting datareader value to a to a Nullable variab

Author  Topic 

Elad BD
Starting Member

1 Post

Posted - 2011-03-23 : 14:57:14
I'm trying to run the following code but get a casting error.
How can I rewrite my code to achive the same ?
[CODE]
boolResult= (bool?)dataReader["BOOL_FLAG"] ?? true;
intResult= (int?)dataReader["INT_VALUE"] ?? 0;[/CODE]


Thanks

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-03-23 : 17:15:53
Do it like this:
boolResult = dataReader["BOOL_FLAG"] != DBNull.Value ? Convert.ToBoolean(dataReader["BOOL_FLAG"]) : 0;

This is for two reasons:
1. When you cast it it is very picky - for example, you cannot cast a decimal(10,0) column to int. But you can use Convert.
2. If the value returned from the query is null (DBNull.Value) you cannot convert it to anything else.
Go to Top of Page
   

- Advertisement -