2011-09-13 72 views
1

的我想提出一個查詢來創建它在SQL進行動態這種查詢

SELECT [att1] 
     ,[att2] 
     ,[att3] 
     ,[att4] 
     ,[att5] 
     ,[att6] 
     ,[att7] 
     ,[att8] 
     ,[att9] 
     ,[att10] 
     ,att11 = att1, 
     att12 = att2, 
     att13 = att3, 
     att14 = att4, 
     att15 = att5, 
     att16 = att6, 
     att17 = att7, 
     att18 = att8, 
     att19 = att9, 
     att20 = att10 
INTO Table_20 
FROM Table_10; 

兩次元素會是什麼使這個充滿活力的最佳方式的表,如果我有一個表30 atts,用30 * 2 atts(兩倍大小)製作表格?

回答

2
DECLARE 
    @table NVARCHAR(512) = N'dbo.Table_10'; 
    @sql NVARCHAR(MAX) = N'', 
    @c  INT; 

SELECT @sql += N',' + name 
    FROM sys.columns 
    WHERE [object_id] = OBJECT_ID(@table) 
    AND name LIKE 'att%'; 

SELECT @c = @@ROWCOUNT; 

SELECT @sql += N',att' + CONVERT(VARCHAR(12), 
     @c + CONVERT(INT, REPLACE(name, 'att', ''))) 
     + ' = ' + name 
    FROM sys.columns 
    WHERE [object_id] = OBJECT_ID(@table) 
    AND name LIKE 'att%'; 

SELECT @sql = N'SELECT ' + STUFF(@sql, 1, 1, '') 
    + ' INTO dbo.Table_20 FROM ' + @table + ';'; 

PRINT @sql; 
-- EXEC sp_executesql @sql;