hello temp11
hello temp11

Reputation: 141

ExecuteScalar retuns NULL value

Stored procedure:

dbo.GetLDate
select DateEntered from Table1 where Id = 4, Gid=5

Result:

Executed Successfully

New query to verify:

DECLARE @LDate datetime
EXEC @LDate =  GetLDate 4,5

Results:

DateEntered
2014-02-13 06:21:43.600

Thus, working fine

Final stored procedure created:

EXEC @LDate =  GetLDate 4,5
Select 1

in C#

int? id = _database.ExecuteScalar() as int?;

Here, every time I get null value only. But I am selecting 1 still I get null value. What could be the reason for this.

Upvotes: 0

Views: 316

Answers (1)

Habib
Habib

Reputation: 223247

You are selecting string '1' and that can't be converted to int? with a cast. Hence you are getting null.

Use:

SELECT 1 --without single quotes

Or you can use Convert.ToInt32 like:

int? id = Convert.ToInt32(_database.ExecuteScalar());

Consider the following example:

object obj = "1";
int? id = obj as int?;

You will get back null as cast from "1" (string) to int/int? will fail.

Upvotes: 5

Related Questions