1

我有一张像

TABLEX-

+------+------------+
| NAME | TABLE_NAME |
+------+------------+
| X1   | X001       |
| X2   | X002       |
+------+------------+

该表包含一个 name 列,它只是描述和一个 table_name 列,它实际上是一个已经存在于数据库中的表。

X001表格有类似的列X1_A, X1_B
X002表格有类似的列X2_A, X2_B

现在我想以TABLE_NAME逗号分隔的字符串连接列中存在的实际表中的所有列,并将其显示为一列。

+------+------------+------------+
| NAME | TABLE_NAME |  COLUMNS   |
+------+------------+------------+
| X1   | X001       | X1_A, X1_B |
| X2   | X002       | X2_A, X2_B |
+------+------------+------------+

现在可以使用 CTE 来实现。我已经使用STUFFwith成功创建了查询XML PATH,但是我遇到了性能问题,因为我上面显示的表中有 200 奇数行,并且每个链接的后续表都有 100 列。

编辑 -

SELECT 
P.NAME,
P.TABLE_NAME,
[COLUMNS]=(SELECT STUFF((SELECT ',' + NAME FROM sys.syscolumns WHERE ID = OBJECT_ID(P.TABLE_NAME) ORDER BY colorder FOR XML PATH('') ), 1, 1,''))
FROM TABLEX P 

TABLEX上面张贴的表格在哪里。

4

1 回答 1

2

试试这个——

DDL:

IF OBJECT_ID (N'dbo.TABLEX') IS NOT NULL
   DROP TABLE TABLEX

IF OBJECT_ID (N'dbo.X001') IS NOT NULL
   DROP TABLE X001

IF OBJECT_ID (N'dbo.X002') IS NOT NULL
   DROP TABLE X002

CREATE TABLE dbo.TABLEX (NAME VARCHAR(50), TABLE_NAME VARCHAR(50))
INSERT INTO dbo.TABLEX (NAME, TABLE_NAME)
VALUES ('X1', 'X001'), ('X2', 'X002')

CREATE TABLE dbo.X001 (X1_A VARCHAR(50), X1_B VARCHAR(50))
CREATE TABLE dbo.X002 (X2_A VARCHAR(50), X2_B VARCHAR(50))

询问:

;WITH cte AS
(
     SELECT 
            NAME
          , TABLE_NAME
          , [COLUMN] = CAST('' AS VARCHAR(1024))
          , POS = 1
     FROM TABLEX t

     UNION ALL

     SELECT 
            t.NAME
          , t.TABLE_NAME
          , CAST([COLUMN] + ', ' + c.name AS VARCHAR(1024))
          , POS + 1
     FROM cte t
     JOIN sys.columns c ON 
                 OBJECT_ID('dbo.' + t.TABLE_NAME) = c.[object_id] 
               AND 
                 t.POS = c.column_id
)
SELECT 
       NAME
     , TABLE_NAME
     , [COLUMNS] = STUFF([COLUMN], 1, 2, '')
FROM (
     SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY POS DESC)
     FROM cte
) t
WHERE t.rn = 1

结果:

NAME   TABLE_NAME    COLUMNS
------ ------------- -------------
X1     X001          X1_A, X1_B
X2     X002          X2_A, X2_B

Query cost:

Query Cost

Statistic:

    Query Presenter  Scans  Logical Reads
-------------------  -----  -------------
                XML      5              9
                CTE      3             48
于 2013-06-18T08:54:44.403 回答