user5582406
user5582406

Reputation:

How to return multiple strings from a MSSQL database in C#

I was using this piece of code until i realized it only returns one piece of information. What is the correct method to use to retrieve multiple items?

sqlconn.Open();
SqlCommand cmd = new SqlCommand("Select [Description] from [dbo].[Categories] ", sqlconn);
string result = (string)cmd.ExecuteScalar();
Console.WriteLine(result);
sqlconn.Close();

I have this ready to take a part an Array i just cant find out how to get it to return an array.

foreach (var item in result)
{
    Console.WriteLine(item);
}

Upvotes: 0

Views: 141

Answers (1)

user5582406
user5582406

Reputation:

ExecuteReader will return multiple items but you need to use a while loop to break down the results.

sqlconn.Open();
SqlCommand cmd = new SqlCommand("Select [Description] from [dbo].[Categories] ", sqlconn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
      Console.WriteLine(reader[0]);
}

Upvotes: 4

Related Questions