user520351
user520351

Reputation:

Is it possible to assign the result of an SQL to a variable?

Can I assign the result of an SQL select command to a local variable in ASP.NET?

Upvotes: 0

Views: 1282

Answers (3)

Robin Orheden
Robin Orheden

Reputation: 2764

SqlCommand.ExecuteScalar is what you are after.

Example:

var command = new SqlCommand("SELECT TOP 1 age FROM example_table");
var ageValue = command.ExecuteScalar() as int?;

Upvotes: 2

Lucero
Lucero

Reputation: 60190

Scalar result: sure, just use ExecuteScalar.

Non-scalar: use a DataSet, or do some processing to build a collection of items containing the data you want

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50215

It sounds like you are looking for ExecuteScalar.

Upvotes: 1

Related Questions