Select column name and value from table

拜拜、爱过 提交于 2019-12-04 16:21:36
Erwin Brandstetter

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.

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