0

我想做一个 SELECT 并从列中获取信息和他的值。我知道我需要访问 *information_schema* 然后我需要在特定行中使用 *column_name* 在内部进行另一个 SELECT 以访问该值。

SELECT column_name,
   DATA_TYPE,
   CHARACTER_MAXIMUM_LENGTH,
   (? ... SELECT COLUMN_NAME FROM MYTABLE ... ?)
FROM information_schema.columns
WHERE table_name = 'MYTABLE'
ORDER BY ordinal_position

如何使用行中的列更改 COLUMN_NAME 以获得结果?

4

2 回答 2

2

如果你的表中有不止一行,我不知道你想要这个。这适用于只有一行的表格。如果表中有不止一行,它将占用表中的一行。

SELECT I.COLUMN_NAME,
       I.DATA_TYPE,
       I.CHARACTER_MAXIMUM_LENGTH,
       (
       SELECT T.X.value('/*[local-name(.)=sql:column("I.COLUMN_NAME")][1]', 'nvarchar(max)')
       FROM 
         (
         SELECT *
         FROM MyTable
         FOR XML PATH(''), TYPE
         ) AS T(X)
       ) AS COLUMN_VALUE
FROM INFORMATION_SCHEMA.COLUMNS AS I
WHERE I.TABLE_NAME = 'MyTable'
ORDER BY I.ORDINAL_POSITION

SQL小提琴

于 2012-07-28T08:36:43.700 回答
0

无论如何,您对如何在 Postgresql 上完成感兴趣:http ://www.sqlfiddle.com/#!1/dea17/1

create table beatles(firstname text,middlename text,lastname text, age int);

insert into beatles(firstname,middlename,lastname,age)
values('John','Winston','Lennon',40);



select c.column_name, x.arr[c.ordinal_position]
from information_schema.columns c
cross join 
    ( select avals (hstore(b)) as arr from (select * from beatles) as b  ) as x
where c.table_schema = 'public' and c.table_name = 'beatles'
order by c.ordinal_position

输出:

| COLUMN_NAME |     ARR |
-------------------------
|   firstname |    John |
|  middlename | Winston |
|    lastname |  Lennon |
|         age |      40 |

现场测试:http ://www.sqlfiddle.com/#!1/dea17/1

于 2012-07-28T09:14:39.000 回答