行智能与sql中的动态列连接?

时间:2015-06-30 14:15:24

标签: sql-server

我需要连接行方式列。我已经完成了,但在我的表中列是静态的,但在我的要求中,列将是动态的。

CREATE TABLE #TEMP
(
ID INT 
,Name VARCHAR (100)
,SNO INT 
,SNO1 INT
,SNO2 INT
)

INSERT INTO #TEMP (ID ,Name,SNO,SNO1,SNO2)
VALUES (1,'SAS',1,2,4),(2,'RAR',5,2,5),(3,'SJS',6,8,6)

SELECT * FROM #TEMP

ID  Name    SNO SNO1 SNO2
1   SAS      1   2     4
2   RAR      5   2     5
3   SJS      6   8     6

SELECT ID,NAME,SNO,(SNO+SNO1)AS SNO1,(SNO+SNO1+SNO2)AS SNO2 FROM #TEMP

ID  NAME    SNO   SNO1     SNO2
1   SAS     1       3         7
2   RAR     5       7         12
3   SJS     6       14        20

1 个答案:

答案 0 :(得分:1)

您可以使用动态SQL。

SQL Fiddle

DECLARE @colNames AS VARCHAR(MAX) = ''
DECLARE @sql AS VARCHAR(MAX) = ''

--Generate the dynamic column names
;WITH CteColumns AS(
    SELECT
        c.name,
        rn = ROW_NUMBER() OVER(ORDER BY c.name)
    FROM sys.columns c
    WHERE 
        c.object_id = object_id('Temp')
        AND c.name LIKE 'SNO%' 
)
SELECT
    @colNames = STUFF((
        SELECT ', ' + colName
        FROM(
            SELECT  
                colName = 
                    ISNULL(
                        (SELECT name + ' + '
                        FROM CteColumns t
                        WHERE t.rn < c1.rn
                        ORDER BY name
                        FOR XML PATH(''))
                    , '') + '' + name + ' AS ' + QUOTENAME(name)
            FROM CteColumns c1
        )t
        FOR XML PATH('')
    ), 1, 2, '')

SELECT @sql = 'SELECT ID, NAME, ' + @colNames + ' FROM Temp'

PRINT @sql
EXEC (@sql)

<强> RESULT

| ID | NAME | SNO | SNO1 | SNO2 |
|----|------|-----|------|------|
|  1 |  SAS |   1 |    3 |    7 |
|  2 |  RAR |   5 |    7 |   12 |
|  3 |  SJS |   6 |   14 |   20 |