Select column name and value from table

Deadly 提交于 2019-12-06 11:07:34

问题


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

回答1:


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.

->SQLfiddle demo.

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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!