开发者

Make dynamic this kind of query

开发者 https://www.devze.com 2023-04-04 19:56 出处:网络
I am making a query to create a table which has twice elements in SQL SELECT [att1] ,[att2] ,[att3] ,[att4]

I am making a query to create a table which has twice elements in 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;

What would be the best way to make this dynamic and if I have a table with 30 atts开发者_开发问答, make a table with 30 * 2 atts (double the size)?


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消