Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data type does the SQLCommand method ExecuteScalar() return?

In SQL Server, ID is a not null integer, and an identity.

When I run the following code, I get an InvalidCastException on the last line:

SqlCommand cmd = new SqlCommand();
cmd.Connection = _conn;
cmd.CommandText = @"INSERT INTO [Users] (Name, Email, Password) VALUES (@name, @email, @pass); SELECT SCOPE_IDENTITY()";
cmd.Parameters.AddWithValue("@name", newUser.Name);
cmd.Parameters.AddWithValue("@email", newUser.Email);
cmd.Parameters.AddWithValue("@pass", newUser.PasswordHash);
int id = (int)cmd.ExecuteScalar();

What is ExecuteScalar() returning here? Whatever its returning has a ToString() that makes it look like a number, so this awful line of code works:

int id = Int32.Parse(cmd.ExecuteScalar().ToString());
like image 524
Patty Avatar asked Oct 18 '10 23:10

Patty


People also ask

What is the return type of ExecuteScalar () method?

The ExecuteScalar method returns as a scalar value the value of the first column of the first row of the result set.

What is use of ExecuteScalar () method?

ExecuteScalar: Use this operation to execute any arbitrary SQL statements in SQL Server to return a single value. This operation returns the value only in the first column of the first row in the result set returned by the SQL statement.

What is the use of ExecuteScalar () function in Ado net?

ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity' . ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable ).

What datatype is returned when calling the ExecuteScalar method of a command object?

Object data type is returned when calling ExecuteScalar method of command object - ADO.NET.


2 Answers

SCOPE_IDENTITY() returns a decimal in code, otherwise known as NUMERIC(38,0) in TSQL.

http://msdn.microsoft.com/en-us/library/ms190315.aspx

So if you want a direct cast, you can do (int)(decimal)cmd.ExecuteScalar();. Note that a decimal to int conversion can lose information in the strictest sense, so just be advised. But with your identity column being an integer, the conversion will be safe.

like image 92
Anthony Pegram Avatar answered Sep 28 '22 10:09

Anthony Pegram


It's probably returning a boxed instance of a different numeric type, such as long.
A boxed long cannot be converted to int.

You can call GetType() on the return value to see what type it really is.

like image 34
SLaks Avatar answered Sep 28 '22 11:09

SLaks