Get field names returned from any sql statement

I want to get a list of field names returned from sql statement. This can be done using the sql statement or some C # parsing code to parse the statement as a string. Can this be done without writing a complex parser?

For example, I can return

name, field2, field3

from

SELECT a.field1 as name, a.field2, b.field3 FROM A INNER JOIN B ON A.Id = B.FkId
+3
source share
3 answers

If you are asking about using SqlClient components like the SqlDataReader Class , you can use

Reader.GetName(columnNumber)

Method to return the column name.

+5
source

DataSet DataTable, Columns, DataColumn. :

// assume dt is DataTable
string colname = dt.Columns[0].ColumnName;
+3

If you use SqlDataReader, which most people have, you can get the field names using the following code

Private Shared Function GetDataRecordColumns(ByVal dr As SqlClient.SqlDataReader) As List(Of String)

    '' list to contain the columns
    Dim ls As New List(Of String)

    For x As Integer = 0 To dr.FieldCount - 1
        ls.Add(dr.GetName(x))
    Next

    Return ls

End Function

If you are using a dataset or datatable, you can use the following function (just pass in your dataset. Table (0) if you are working with a dataset)

Private Shared Function GetDataRecordcolumns(ByVal dt As DataTable) As List(Of String)

        Dim ls As New List(Of String)

        For Each col As DataColumn In dt.Columns
            ls.Add(col.ColumnName)
        Next

        Return ls

 End Function

Hope this helps

FROM

0
source

Source: https://habr.com/ru/post/1724022/


All Articles