-2

I have a table of students in SQL Server and I want to execute a query like

SELECT * 
FROM tbl_students;

but I don't want to write each column number getValue(0) getValue(1) in C# to get the result,

I wrote in the following statement

Console.WriteLine("{0},\t{1}", sqlDReader.GetValue(0), sqlDReader.GetValue(1));

I just want to get all the column values without writing each column index number, can't we simply get a string of the complete record, preferably with spaces of tabs in between?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

You can. Assuming you are using c#, something like this would work

If you know the number of columns:

string completeLine = "";
for(int i = 0 ; i < numCols ; i++)
{
    completeLine += sqlDReader.GetValue(0).ToString();
    if (i < numCols - 1)
        completeLine += " ";
}
Console.WriteLine (completeLine);

This assumes all columns can be cast to a string. Also assumes you know number of columns. There's a bunch of more complex ways to do this.

To get number of rols you can get the .Columns.Count or similar.

Then have an outer loop, for each row. Note: do not try to do this type of string concatenation on the entire table as it will be slow (since string are really not changeable).

drHodge
  • 76
  • 8