If I have the following table in a PostgreSQL database:
Col1 Col2 Col3
A a 1
B b 2
Is there a way to get the column name for each value without explicitly specifying the column names? I.e. have a result set like:
Col1 A
Col1 B
Col2 a
Col2 b
Col3 1
Col3 2
Of course, you could write a PL/pgSQL function and query the catalog table pg_attribute
yourself. But it's so much easier with one of the following:
JSON
The function row_to_json()
provides functionality that goes half the way. Introduced with Postgres 9.2:
SELECT row_to_json(t, TRUE) FROM tbl t;
You don't have to mention the column names at all, the function derives them from the table type.
But you'll need json_each_text()
from Postgres 9.3 to go all the way:
SELECT json_each_text(row_to_json(t)) FROM tbl t;
To get a sort order like you display:
SELECT (json_each_text(row_to_json(t))).*
FROM tbl t
ORDER BY 1, 2;
(It's unclear how you want to sort exactly.)
Untested. SQLfiddle does not provide Postgres 9.3, yet.
hstore
However, you can do the same with the additional module hstore. Available since 8.4. Install it once with:
CREATE EXTENSION hstore;
Details:
Key value pair in PostgreSQL
Query:
SELECT (each(hstore(t))).*
FROM tbl t
ORDER BY 1,2;
That's all.
Again, no SQLfiddle, since one can't install additional modules there.
You can get column names from reader in c#
string CONNECTION_QUERY = "SELECT * FROM FINANCE_PAYMENTS";
SqlCommand comand = new SqlCommand(CONNECTION_QUERY,onnection);
SqlDataReader reader = comand.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
//this line will give you Column name and value
JO.Add(reader.GetName(i),reader[i].ToString());
}
}
来源:https://stackoverflow.com/questions/18991334/select-column-name-and-value-from-table