选择以逗号分隔的列名

时间:2016-03-16 19:26:26

标签: sql sql-server

我想编写一个SQL语句(SQL Server),它在特定条件下选择列名,并“返回”由,分隔的所有列名。

SELECT COLUMN_NAME 
FROM all_tab_columns 
WHERE OWNER = 'KOCH' AND TABLE_NAME = 'TABLE1';

这会返回几行列名:

NAME
ID
STATE
CITY

但是我想让它们以这种格式返回:

NAME, ID, STATE, CITY

(我想我必须使用FROM dual)?

1 个答案:

答案 0 :(得分:0)

For Oracle:

;WITH CTE_Columns (column_list, column_id) AS
(
    SELECT
        CAST(COLUMN_NAME AS VARCHAR(500)) AS column_list,
        COLUMN_ID
    FROM USER_TAB_COLUMNS C
    WHERE
        TABLE_NAME = 'TABLE1' AND
        COLUMN_ID= 1
    UNION ALL
    SELECT
        CAST(column_list + ', ' + C.COLUMN_NAME AS VARCHAR(500)),
        C.COLUMN_ID
    FROM
        CTE_Columns CL
    INNER JOIN USER_TAB_COLUMNS C ON
        C.TABLE_NAME = 'TABLE1' AND
        C.COLUMN_ID = CL.COLUMN_ID + 1
)
SELECT column_list
FROM CTE_Columns
WHERE
    COLUMN_ID =
          (
              SELECT MAX(COLUMN_ID)
              FROM USER_TAB_COLUMNS
              WHERE TABLE_NAME = 'TABLE1')