在SQL Server 2008中使用先前选定的值嵌套SELECT

时间:2012-05-28 13:20:42

标签: sql-server-2008 sql

我想制作一个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以获得结果?

2 个答案:

答案 0 :(得分: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 Fiddle

答案 1 :(得分: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